我在这段代码中缺少什么,它看起来不错并且格式正确吗?

时间:2021-07-14 03:49:17

标签: input uppercase

编写一个输入文本文件的程序。程序应按字母顺序打印文件中的唯一单词。大写单词应优先于小写单词。例如,'Z' 出现在 'a' 之前。

输入文件可以包含一个或多个句子,或者是多行单词列表。

“敏捷的棕色狐狸跳过懒狗”

import torchvision
import torch
from tensorboardX import SummaryWriter
import torch.nn as nn
model = torchvision.models.resnet50(pretrained=False)
dummy_input=torch.rand((10, 3, 224, 224))
with SummaryWriter(comment='Net1')as w:
    w.add_graph(model, (dummy_input,))

2 个答案:

答案 0 :(得分:0)

首先,在读取文件时,您可以做一些更简单的事情来获取每个连续单词的列表。即,

fname = input("Enter the input filename: ") # get the filename

f = open(fname, 'r') # open the file
contents = f.read() # read the file contents
f.close() # close the file (you didn't before)

all_words = contents.split(' ') # get every word in original order

至于排序,这似乎没问题。但是,在创建包含所有唯一值的唯一单词列表时,您可以使用一个简单的技巧:unique = list(set(sorted(all_words)))。简而言之,set 类型的每个唯一值只能有 1 个。因此,如果将其转换为集合,然后再转换回列表,则会得到按字母顺序排列的所有唯一值的列表。 sorted 函数返回列表的排序版本,而 list.sort 对列表进行排序,不返回任何内容。

最后,请记住始终关闭尚未关闭的文件。

最重要的是,考虑注释一些代码以帮助未来的读者理解它的每个部分的含义,并不时包含一些空格(即空格、换行符)以分隔不同的部分并使其看起来只是一个好一点。不过我能想到的就这些了。<​​/p>

编辑: 我意识到我应该包含修改后代码的汇总版本,所以这里是:

fname = input("Enter the input filename: ") # get the filename

f = open(fname, 'r') # open the file
contents = f.read() # read the file contents
f.close()

all_words = contents.split(' ') # get every word in original order
unique_words = list( set( sorted( all_words ) ) ) # sort the words, then convert it to a set type which can only contain 1 of each unique value, and convert it back to a list

for word in unique_words:
    print word # print every unique word

答案 1 :(得分:0)

我希望我像你提到的那样进行了编辑,但在对我的代码进行了一些更改后,这对我有用。

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()
相关问题