怎么制作一个始终被记住的清单?

2024-09-30 20:39:14 发布

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

我一直在给你取名_列表.txt每次我都要存储文档信息以便以后记住。然而,我觉得有一种更有效的方法来记住一个列表,而不是扫描一个文档,看看一个单词是否已经存在,如果没有,就把它添加到末尾。以下是我通常使用的代码:

def noun_dict(word):  # Searches to see if the word is already a noun, if not, adds it.
    from string import ascii_letters
    nouns = []
    with open("word_types_nouns.txt", "r") as f:
        lines = f.readlines()
        x = 0
        for line in lines:  # Notice 'words' is different than 'word'
            words = [word for word in line.split() if all(ch in ascii_letters for ch in word)]
            x += 1
            nouns.append(words[0])
        nouns.sort()
        if nouns.count(word) == 0:
            nouns.append(word)
            with open("word_types_nouns.txt", "a") as file:
                file.write("\n" + str(word))
            print(word[0].capitalize() + word[1:], "added as a noun.")
        else:
            print(word[0].capitalize() + word[1:], "already identified as a noun.")
        return nouns

Tags: in文档txt列表forifisas