input - 我在这段代码中遗漏了什么,它看起来不错并且格式正确吗?
问题描述
编写一个输入文本文件的程序。程序应按字母顺序打印文件中的唯一单词。大写单词应优先于小写单词。例如,“Z”出现在“a”之前。
输入文件可以包含一个或多个句子,或者是多行单词列表。
“敏捷的棕色狐狸跳过了懒狗”
textFileName = input("Enter the input file name: ")
textFile = open(textFileName, 'r')
listOfWords = []
while True:
line = textFile.readline()
if line == "":
break
else:
words = line.split()
for word in words:
listOfWords.append(word)
listOfWords.sort()
uniqueListOfWords = []
for count in range(len(listOfWords) -1):
if listOfWords[count]!= listOfWords[count + 1]:
uniqueListOfWords.append(listOfWords[count])
uniqueListOfWords.append(listOfWords[len(listOfWords) -1])
print(word)
解决方案
我希望我像你提到的那样进行了编辑,但是在对我的代码进行了一些更改后,这对我有用。
def sorted_unique_file(input_filename):
input_file = open(input_filename, 'r') #open file in read mode
file_contents = input_file.read() #read text from file
input_file.close()
unique = []
word_list = file_contents.split()
for word in word_list:
if word not in unique:
unique.append(word) #add unique words into list
print("unique words in alphabetical order are: ")
print("\n".join(sorted(list(set(unique))))) #sort the words using set operation
def main():
filename = input("Enter the input file name: ") #read the file name
sorted_unique_file(filename) #call the function to print unique words in alphabetical order
if __name__ == "__main__":
main()
推荐阅读
- android - 谷歌应用内计费,举杯打破一切
- arrays - 对多维数组求和 - Excel VBA
- java - 试图理解与多个对象的线程间通信
- java - 模块中的 Eclipse 错误,我的格式不正确吗?
- javascript - 从 div 中选择和选择
- error-handling - 在 rhs 生产中匹配错误时在 Yacc/Bison 中删除令牌
- python - 从用户数据库 django 获取单个值
- pytest - 如何使用 pytest-asyncio 更改或检查测试的顺序
- google-cloud-dataflow - 使用 DataFlow 运行器运行 Beam 作业时出错(使用 Bazel):未找到模块错误
- r - 计算列的特定值