gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 06:26:06 26 4
gpt4 key购买 nike

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

Here is a sample output: Analyze what file: itsy_bitsy_spider.txt
Concordance for file itsy_bitsy_spider.txt itsy : Total Count: 2 Line:1: The ITSY Bitsy spider crawled up the water spout Line:4: and the ITSY Bitsy spider went up the spout again

#this function will get just the unique words without the stop words. 
def openFiles(openFile):

for i in openFile:
i = i.strip()
linelist.append(i)
b = i.lower()
thislist = b.split()
for a in thislist:
if a in stopwords:
continue
else:
wordlist.append(a)
#print wordlist




#this dictionary is used to count the number of times each stop
countdict = {}
def countWords(this_list):
for word in this_list:
depunct = word.strip(punctuation)
if depunct in countdict:
countdict[depunct] += 1
else:
countdict[depunct] = 1

最佳答案

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]))

关于python - 我有一个 txt 文件。如何获取字典键值并打印它们出现的文本行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7961859/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com