需要返回完整的单词,而不仅仅是第一个字母

Need to have the full word come back instead of just the first letter

提问人:Spudnick9 提问时间:11/17/2023 最后编辑:PM 77-1Spudnick9 更新时间:11/17/2023 访问量:37

问:

##Write a program that inputs a text file. 
##The program should print the unique words in the file in alphabetical order. 
##Uppercase words should take precedence over lowercase words. For example, 'Z' comes before 'a'.
## The quick brown fox jumps over the lazy dog

    file_words = open("Words.txt", 'r+')
    words_list = []
    first_val_list = []

    for line in file_words:
        for word in line.split():
            words_list.append(word)

    for word in words_list:
        first_val = word[0]
        ascii = ord(first_val)
        first_val_list.append(first_val)

    first_val_list.sort(reverse=False)

现在这输出 ['T', 'b', 'd', 'f', 'j', 'l', 'o', 'q', 't'],这是我需要它做的,但使用整个单词。 例如 ['The', 'Brown', 'dog', 'fox', 'jumps', 'lazy', 'over', 'quick', 'the']

first_val_list的印刷品只是为了看看我到目前为止所拥有的是否有效。 那么我如何才能将完整的单词恢复到第一个字母上 我是编程新手,有大约 10 周的经验,所以请像我 5 岁一样解释一下。

Python 排序 ASCII

评论

3赞 Scott Hunter 11/17/2023
你认为有什么作用?如果你从不使用它,你为什么要计算?first_val = word[0]ascii
0赞 PM 77-1 11/17/2023
您的代码看起来像 ,所以我添加了标签。如果我错了,请输入正确的。Python
0赞 Stef 11/17/2023
“print the unique words in the file” 是什么意思?如果一个单词在文本文件中有重复项,这是否意味着您根本不应该打印它?还是打印一次?

答:

1赞 Barmar 11/17/2023 #1

first_val是单词的第一个字母。所以你只把第一个字母放到列表中,而不是整个单词。

您也不会删除重复项。您可以通过将单词列表转换为集合来执行此操作。

with open("words.txt") as file_words:
    words_list = file_words.read().split()

unique_words = set(words_list)
sorted_words = sorted(unique_words)