提问人:Spudnick9 提问时间:11/17/2023 最后编辑:PM 77-1Spudnick9 更新时间:11/17/2023 访问量:37
需要返回完整的单词,而不仅仅是第一个字母
Need to have the full word come back instead of just the first letter
问:
##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 岁一样解释一下。
答:
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)
评论
first_val = word[0]
ascii
Python