Skip to main content
 首页 » 编程设计

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

2025年05月04日9daizhj

我有一个 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]))