Skip to main content
 首页 » 编程设计

python之找出只出现一次的词

2025年05月04日10yyy_WW

我只检索文件中的唯一单词,这是我目前所拥有的,但是就大 O 符号而言,是否有更好的方法在 python 中实现这一点?现在这是 n 的平方

def retHapax(): 
    file = open("myfile.txt") 
    myMap = {} 
    uniqueMap = {} 
    for i in file: 
        myList = i.split(' ') 
        for j in myList: 
            j = j.rstrip() 
            if j in myMap: 
                del uniqueMap[j] 
            else: 
                myMap[j] = 1 
                uniqueMap[j] = 1 
    file.close() 
    print uniqueMap 

请您参考如下方法:

如果你想找到所有唯一的单词,并认为 foo 与 foo. 相同,你需要去除标点符号。

from collections import Counter 
from string import punctuation 
 
with open("myfile.txt") as f: 
    word_counts = Counter(word.strip(punctuation) for line in f for word in line.split()) 
 
print([word for word, count in word_counts.iteritems() if count == 1]) 

如果你想忽略大小写你还需要使用line.lower()。如果您想准确地获得唯一的单词,那么涉及的不仅仅是在空格上拆分行。