为什么我的函数要打印一个额外的列表作为输出?

2024-09-28 22:15:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个函数,它读取一个.txt文件并返回N个最常用单词的列表。然而,我的代码和最长单词的列表一起工作,它还打印出了在此之前文件中所有单词的列表,我不知道为什么。如果有人能告诉我是哪条线造成的,我将不胜感激。代码如下:

with open(filename, 'r') as myFile:
    fileText = myFile.read().splitlines()


listOfLines = []
listOfWords = []

for lineNum in range(len(fileText)):
    listOfLines.append(fileText[lineNum].split())

for line in listOfLines:
    for word in line:
        for c in string.punctuation:
            word = word.replace(c, "")
        listOfWords.append(word)

uniqueWords = []

for word in listOfWords:
    if word not in uniqueWords:
        uniqueWords.append(word)

if N > len(uniqueWords):
    print("[Error] The", filename, "contains", len(uniqueWords), "unique words (you asked for ", N, ").")
    return None
else:
    longestWords = []
    wordValPairs = [ [freq, word] for word, freq in wordFrequency(filename).items()]
    wordValPairs.sort()
    for i in range(N):
        longestWords.append(wordValPairs[-1][1])
        wordValPairs.pop()

    return longestWords

我用来测试的文件包含以下文本:

你好,你好,世界! 我叫克里斯

调用函数返回:

['hello'、'hello'、'hello'、'world'、'My'、'My'、'My'、'name'、'is'、'Chris'、'Chris'、'Chris'、'Chris'、'Chris'、'Chris'、'Chris'、'Chris'] [“克里斯”,“我的”]

我只想把第二张单子还给你。你知道吗

非常感谢!你知道吗


Tags: 文件in列表forlenfilename单词word