Python 我有一个txt文件。如何获取字典键值并打印它们出现的文本行?

Python 我有一个txt文件。如何获取字典键值并打印它们出现的文本行?,python,Python,我有一个txt文件。我已经编写了代码,可以找到唯一的单词以及每个单词在该文件中出现的次数。我现在需要弄清楚如何打印出这些单词所对应的行。我该怎么做呢 以下是一个示例输出: 分析哪个文件:itsy\u bitsy\u spider.txt 文件itsy\u bitsy\u spider.txt的一致性 伊西:总数:2 台词:1:那只小蜘蛛爬上了水嘴 台词:4:那只小蜘蛛又爬上了喷口 如果逐行解析输入文本文件,则可以维护另一个字典,即word->List映射。即为一行中的每个单词添加一个条目。可能看

我有一个txt文件。我已经编写了代码,可以找到唯一的单词以及每个单词在该文件中出现的次数。我现在需要弄清楚如何打印出这些单词所对应的行。我该怎么做呢

以下是一个示例输出: 分析哪个文件:itsy\u bitsy\u spider.txt
文件itsy\u bitsy\u spider.txt的一致性 伊西:总数:2 台词:1:那只小蜘蛛爬上了水嘴 台词:4:那只小蜘蛛又爬上了喷口


如果逐行解析输入文本文件,则可以维护另一个字典,即word->List映射。即为一行中的每个单词添加一个条目。可能看起来像下面这样。请记住,我对python不是很熟悉,所以可能会错过一些语法捷径

乙二醇

您可能需要做的一个修改是,如果一个单词在行中出现两次,则防止将重复项添加到linedict中


上面的代码假设您只想读取文本文件一次。

您能给我们展示一些输入和输出示例吗?如果
“一致性”
意味着输出时单词应按字母顺序排序。否,我正在阅读多个文本文件。我将添加我的代码的其余部分,以了解我的情况。从那里,我需要在文本文件中找到我的countdict键,并打印它们出现的行。这仍然适用于多个文本文件,您只需为每个文件调用一次,并使用相同的词典。您可以轻松修改此项,以便在之后从“单词”dict中删除常用单词。谢谢,这很有帮助。我仍在试图找出如何利用我所拥有的来获得所需的输出。@SimplyZ:你还不应该接受这个答案(一两天后,如果它仍然是最好的,那么接受它就好了)。它不满足您的问题要求,例如,
停止词
,缺少行号。将它与我在你的问题评论中链接的代码进行比较。我接受了它,因为它引导我走上了正确的道路,我的作业昨天就要交了。我已经有了一个停止词的方法。不过,我会仔细阅读其余的评论,并选择最好的方法。谢谢
openFile = open("test.txt", "r")

words = {}

for line in openFile.readlines():
  for word in line.strip().lower().split():
    wordDict = words.setdefault(word, { 'count': 0, 'line': set() })
    wordDict['count'] += 1
    wordDict['line'].add(line)

openFile.close()

print words
countdict = {}
linedict = {}
for line in text_file:
    for word in line:
         depunct = word.strip(punctuation)
         if depunct in countdict:
             countdict[depunct] += 1
         else:
             countdict[depunct] = 1

         # add entry for word in the line dict if not there already
         if depunct not in linedict:
             linedict[depunct] = []

         # now add the word -> line entry
         linedict[depunct].append(line)
openFile = open("test.txt", "r")

words = {}

for line in openFile.readlines():
  for word in line.strip().lower().split():
    wordDict = words.setdefault(word, { 'count': 0, 'line': set() })
    wordDict['count'] += 1
    wordDict['line'].add(line)

openFile.close()

print words
from collections import defaultdict

target = 'itsy'
word_summary = defaultdict(list)
with open('itsy.txt', 'r') as f:
    lines = f.readlines()

for idx, line in enumerate(lines):
    words = [w.strip().lower() for w in line.split()]
    for word in words:
        word_summary[word].append(idx)

unique_words = len(word_summary.keys()) 
target_occurence = len(word_summary[target]) 
line_nums = set(word_summary[target])

print "There are %s unique words." % unique_words 
print "There are %s occurences of '%s'" % (target_occurence, target) 
print "'%s' is found on lines %s" % (target, ', '.join([str(i+1) for i in line_nums]))