соответствующий контент создает новый столбец - PullRequest
0 голосов
/ 23 октября 2019

Здравствуйте, у меня есть набор данных, в котором я хочу сопоставить свое ключевое слово с местоположением. У меня проблема с местоположением «Афганистан», «Кабул» или «Гельмунд», которое у меня есть в моем наборе данных, и которое встречается в более чем 150 комбинациях, включая орфографические ошибки, использование заглавных букв и название города или города. То, что я хочу сделать, это создать отдельный столбец, который возвращает значение 1, если какой-либо из этих символов «afg» или «Afg» или «kab» или «helm» или «содержится в месте. Я не уверен, если верхний илинижний регистр имеет значение.

Например, существуют сотни комбинаций местоположений, таких как: Джегдалак, Афганистан, Афганистан, Газни ♥, Кабул / Афганистан,

Я пробовал этот код, и онхорошо, если оно точно соответствует фразе, но слишком много вариаций, чтобы записать каждое исключение

keywords= ['Afghanistan','Kabul','Herat','Jalalabad','Kandahar','Mazar-i-Sharif', 'Kunduz', 'Lashkargah', 'mazar', 'afghanistan','kabul','herat','jalalabad','kandahar']


#how to make a column that shows rows with a certain keyword..
def keyword_solution(value):
    strings = value.split()
    if any(word in strings for word in keywords):
        return 1
    else:
        return 0

taleban_2['keyword_solution'] = taleban_2['location'].apply(keyword_solution)

# below will return the 1 values

taleban_2[taleban_2['keyword_solution'].isin(['1'])].head(5)

Просто нужно заменить эту логику, где все результаты будут помещены в столбец "keyword_solution", который соответствует либо "Afg"или «афг» или «каб» или «каб» или «кунд» или «кунд»

1 Ответ

0 голосов
/ 23 октября 2019

С учетом следующего:

  • Предложения от New York Times
  • Удалите все не алфавитно-цифровые символы
  • Измените все на строчные, тем самым устраняя необходимостьразличные варианты слов
  • Разбить предложение на list или set. Я использовал set из-за длинных предложений.
  • При необходимости добавьте в список keywords
  • Соответствующие слова из двух списков
    • 'afgh' in ['afghanistan']: False
    • 'afgh' in 'afghanistan': True
    • Таким образом, поиск по списку ищет каждое ключевое слово в каждом слове word_list.
    • [True if word in y else False for y in x for word in keywords]
    • Это позволяет сократить список ключевых слов (т. Е. Указывать afgh, afghanistan не требуется)
import re
import pandas as pd

keywords= ['jalalabad',
           'kunduz',
           'lashkargah',
           'mazar',
           'herat',
           'mazar',
           'afgh',
           'kab',
           'kand']

df = pd.DataFrame({'sentences': ['The Taliban have wanted the United States to pull troops out of Afghanistan Turkey has wanted the Americans out of northern Syria and North Korea has wanted them to at least stop military exercises with South Korea.',
                                 'President Trump has now to some extent at least obliged all three — but without getting much of anything in return. The self-styled dealmaker has given up the leverage of the United States’ military presence in multiple places around the world without negotiating concessions from those cheering for American forces to leave.',
                                 'For a president who has repeatedly promised to get America out of foreign wars, the decisions reflect a broader conviction that bringing troops home — or at least moving them out of hot spots — is more important than haggling for advantage. In his view, decades of overseas military adventurism has only cost the country enormous blood and treasure, and waiting for deals would prolong a national disaster.',
                                 'The top American commander in Afghanistan, Gen. Austin S. Miller, said Monday that the size of the force in the country had dropped by 2,000 over the last year, down to somewhere between 13,000 and 12,000.',
                                 '“The U.S. follows its interests everywhere, and once it doesn’t reach those interests, it leaves the area,” Khairullah Khairkhwa, a senior Taliban negotiator, said in an interview posted on the group’s website recently. “The best example of that is the abandoning of the Kurds in Syria. It’s clear the Kabul administration will face the same fate.”',
                                 'afghan']})

# substitute non-alphanumeric characters
df['sentences'] = df['sentences'].apply(lambda x: re.sub('[\W_]+', ' ', x))

# create a new column with a list of all the words
df['word_list'] = df['sentences'].apply(lambda x: set(x.lower().split()))

# check the list against the keywords
df['location'] = df.word_list.apply(lambda x: any([True if word in y else False for y in x for word in keywords]))

# final
print(df.location)

0     True
1    False
2    False
3     True
4     True
5     True
Name: location, dtype: bool
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...