Хотите сопоставить и посчитать весь текст или слова словаря с поиском текста в Python - PullRequest
0 голосов
/ 18 февраля 2019

У меня есть 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, .... слова.и где мы добавим код решения в приведенном выше коде.

Одна логика на мой взгляд, если какое-либо ключевое слово содержит более одного слова, то во время поиска, если слово этого конкретного ключевого слова соответствует, тогда код проверяет следующее слово изискать текст по ключевым словам, если совпадает, тогда хорошо, в противном случае перейти к следующему ключевому слову.

1 Ответ

0 голосов
/ 23 февраля 2019

Ну, нелегко понять, что вы пытались сделать.И я не уверен, что вы понимаете, что такое файл CSV.Попробуйте открыть его в том же редакторе ( не Excel), в котором вы редактируете свой скрипт Python.

В любом случае, вот моя попытка:

import csv
import time

with open('country names.txt', 'r') as f:
    all_keywords = list(line.lower().rstrip("\n") for line in f)

with open('Detail_file.csv', newline='') as csvfile:
    reader = csv.DictReader(csvfile)
    full_rows = [(row['sr. no.'], row['Details'], row['LOC']) for row in reader]

time_string = time.strftime("%Y-%m-%d-(%H-%M-%S)")
filename = 'output-' + time_string + '.csv'

with open(filename, 'w', newline='') as csvfile:

    writer = csv.writer(csvfile)
    writer.writerow(['sr. no.', 'Details', 'LOC', 'Placename'])

    for input_row in full_rows:
        stored_matches_unique = set(x for x in all_keywords if x in input_row[1].lower())
        stored_matches = list(stored_matches_unique)
        new_row = input_row + stored_matches
        writer.writerow(new_row)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...