У меня есть 2 файла, один из них - .txt файл, который содержит название страны, а другой - файл csv, который содержит детали (текст).Я хочу сопоставлять названия стран строка за строкой из текстового CSV-файла, подсчитывать и распечатывать совпадающие слова
Я попробую этот код:
#NEW!
import csv
import time
#OLD! Import the keywords
f = open('country names.txt', 'r')
allKeywords = f.read().lower().split("\n")
f.close()
#CHANGED! Import the 'Details' column from the CSV file
allTexts = []
fullRow = []
with open('Detail_file.csv') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
#the full row for each entry, which will be used to recreate the improved CSV file in a moment
fullRow.append((row['sr. no.'], row['Details'], row['LOC']))
#the column we want to parse for our keywords
row = row['Details'].lower()
allTexts.append(row)
#NEW! a flag used to keep track of which row is being printed to the CSV file
counter = 0
#NEW! use the current date and time to create a unique output filename
timestr = time.strftime("%Y-%m-%d-(%H-%M-%S)")
filename = 'output-' + str(timestr) + '.csv'
#NEW! Open the new output CSV file to append ('a') rows one at a time.
with open(filename, 'a') as csvfile:
#NEW! define the column headers and write them to the new file
fieldnames = ['sr. no.', 'Details', 'LOC', 'Placename']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
#NEW! define the output for each row and then print to the output csv file
writer = csv.writer(csvfile)
#OLD! this is the same as before, for currentRow in fullRow:
for entry in allTexts:
matches = 0
storedMatches = []
#for each entry:
allWords = entry.split(' ')
for words in allWords:
#if a keyword match is found, store the result.
if words in allKeywords:
if words in storedMatches:
continue
else:
storedMatches.append(words)
matches += 1
#CHANGED! send any matches to a new row of the csv file.
if matches == 0:
newRow = fullRow[counter]
else:
matchTuple = tuple(storedMatches)
newRow = fullRow[counter] + matchTuple
#NEW! write the result of each row to the csv file
writer.writerows([newRow])
counter += 1
хорошо работает и выводится введите описание изображения здесь
, поэтому у меня проблема в том, что если мое ключевое слово (название страны) содержит одно слово, например, Австралия, Америка и т. Д., Его работа хороша, НО
, если мойсловарь любое ключевое слово содержит более 1 слова, например, Новая Зеландия, Южная Африка и т. д. его не совпадают и не учитываются, поэтому у меня возникла эта проблема, потому что приведенный выше код работает над сопоставлением слов, поэтому как решить эту проблему, если мой словарь содержит любое ключевое словоболее 1 слова, как conatins 2, 3, 4, .... слова.и где мы добавим код решения в приведенном выше коде.
Одна логика на мой взгляд, если какое-либо ключевое слово содержит более одного слова, то во время поиска, если слово этого конкретного ключевого слова соответствует, тогда код проверяет следующее слово изискать текст по ключевым словам, если совпадает, тогда хорошо, в противном случае перейти к следующему ключевому слову.