Py学习  »  Python

如何索引Python中每行有多个单词的输入单词

DSMK Swab • 4 年前 • 1595 次点击  

本守则的目的是通读下列句子: test.txt 检查每个单词是否正确 test_oov.txt 有一个例句是 测验txt

一个示例输入文件是

joe biden is the us president
john mccain was a congressman
jpmorgan chase is the way to go
this is an irrelevant sentence
kanye west is an artist

测试一下。txt将是

joe biden
john mccain
johns hopkins university
johnson johnson
jpmorgan chase
justice department
kamala harris
kanye west

它应该是输出的

joe biden : joe biden is the us president
john mccain : john mccain was a congressman
etc.

然而,当 测试一下。txt 输入每行有多个单词。当一个单词只是一个单词时,它就很好用了。然而,如果是这样的话, Joe Biden, or John mccain etc, 这不管用。

代码如下

from nltk.tokenize import sent_tokenize, word_tokenize

# 1. create a reusable word index like {'worda': [2, 4, 10], 'wordb': [1, 9]}
with open("test.txt", "r", encoding="utf8") as fp:
    news_sentences = sent_tokenize(fp.read())

index = {}
for i, sentence in enumerate(news_sentences):
    for word in word_tokenize(sentence):
        word = word.lower()
        if word not in index:
            index[word] = []
        index[word].append(i)

# 2. look up words from that index and retrieve the associated sentences
with open("test_oov.txt", "r", encoding="utf8") as fp:
    oov_ner_data = [l.strip() for l in fp.readlines()]

matches = {}

for word in oov_ner_data:
    word = word.lower()
    if word in index:
        matches[word] = [news_sentences[i] for i in index[word]]

for (key, value) in matches.items():
    print(key + " : " + str(value))

我该怎么解决这个问题?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/133634
文章 [ 3 ]  |  最新文章 4 年前
Muhd Mairaj
Reply   •   1 楼
Muhd Mairaj    5 年前

我不明白你为什么需要为此导入任何库/模块

import pprint # And ofcourse i import pprint just as i say that you dont need any importing, lol, this makes the printed dict look better in the terminal

matches = {}

# First store all the new sentences as a list
with open("test.txt", "r") as test:
    new_sentences = test.read().split("\n")
    # For checking without case sensitivity while also maintaining the original list
    new_sentences_lower = [item.lower() for item in new_sentences] 

# Second, store all the keys as a list
with open("test_oov.txt") as test_oov:
    stored_keys = test_oov.read().split("\n")
    # Again, to prevent case sensitivity and maintain original
    stored_keys_lower = [item.lower() for item in stored_keys]

# i and j are the indices of key and sentence respectively
for i, key in enumerate(stored_keys_lower):
    for j, sentence in enumerate(new_sentences_lower):
        if key in sentence: 
            matches.update({stored_keys[i]: new_sentences[j]})

pprint.pprint(matches)

如果你希望每个键都有一个以上的例句,那么最好先把所有键和值列成一个列表

在上述代码中的for循环之前,您可以执行以下操作:

for key in stored_keys:
   matches.update({key: []})

这将返回(使用pprint):

{'Joe biden': [],
 'john mccain': [],
 'johns hopkins university': [],
 'johnson johnson': [],
 'jpmorgan chase': [],
 'justice department': [],
 'kamala harris': [],
 'kanye west': []}

在此之后,一个类似于之前的代码,除了我们在列表中附加了匹配的判决:

for i, key in enumerate(stored_keys_lower):
    for j, sentence in enumerate(new_sentences_lower):
        if key in sentence: 
            matches[stored_keys[i]].append(new_sentences[j])

pprint.pprint(matches)

最终输出:

{'Joe biden': ['joe biden is the us president'],
 'john mccain': ['john mccain was a congressman'],
 'johns hopkins university': [],
 'johnson johnson': [],
 'jpmorgan chase': ['jpmorgan chase is the way to go'],
 'justice department': [],
 'kamala harris': [],
 'kanye west': ['kanye west is an artist']}
Joffan
Reply   •   2 楼
Joffan    5 年前

如果您想输出包含每次搜索中所有单词的每个句子,可以构建一个查找相关字符串的词典,然后缩小范围,只输出包含所有所需单词的项目。

news_sentences = '''Joe Biden is the us president
John McCain was a congressman
JPMorgan Chase is the way to go
This is an irrelevant sentence
Kanye West IS an artist'''.split('\n')


from collections import defaultdict

newsDict = defaultdict(set)
for sentence in news_sentences:
    for word in sentence.split():
        newsDict[word.lower()].add(sentence)
#
oov_ner_data = input('test, hit me: ').split()

report = newsDict[oov_ner_data[0].lower()].copy()
for word in oov_ner_data[1:]:
    report &= newsDict[word.lower()]

if report:
    print(*report,sep='\n')
else:
    print("Good news")

如果搜索词恰好出现在一个不相关的句子中,就有可能出现“假新闻”。你可以限制每个新闻句子的扫描量,但在我看来,关键词原则上可以出现在任何地方。您还可以在新闻解析和输入时潜在地丢弃常用词。

BuddyBob
Reply   •   3 楼
BuddyBob    5 年前

这是我自制的食谱。

dictEx = {names:sent for names in set([x.strip() for x in open('names.txt','r')]) for sent in [y.strip() for y in open('sentence.txt','r')] if names in sent}

输出

{'joe biden': 'joe biden is the us president', 'john mccain': 'john mccain was a congressman', 'jpmorgan chase': 'jpmorgan chase is the way to go', 'kanye west': 'kanye west is an artist'}

现在,如果在 names.txt 你有多个名字。上面的代码将解决这个问题。 但是假设你有多个句子 sentence.txt .这是个问题,上面的代码对此不起作用。相反,你可以尝试以下方法。

nameList = set([x.strip() for x in open('names.txt','r')])
sentences = [y.strip() for y in open('sentence.txt','r')]
dictEx = {}
for names in nameList:
    for sent in sentences:
        if names in sent and names in dictEx.keys():dictEx[names].append(sent)
        elif names in sent and names not in dictEx.keys():dictEx[names] = [sent]
print(dictEx)