##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'],这就是我需要它做的但整个词。 例如, [‘那个’、‘棕色’、‘狗’、‘狐狸’、‘跳跃’、‘懒惰’、‘越过’、‘快’、‘那个’]
打印first_val_list只是为了看看我到目前为止所拥有的是否有效。 那么我怎样才能将完整的单词恢复到第一个字母上 一般来说,我是编程新手,大约有 10 周的经验,所以请像我 5 岁一样解释一下。
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)