简体   繁体   English

如何在python的输出中使此字母列表看起来更好

[英]How can I make this alphabetical list look nicer in the output in python

It works for the most part but the output looks well messy as hell so how might I be able to clean it up I would also like to know how to phrase the pseudocode if possible. 它在大多数情况下都有效,但是输出看起来像地狱般凌乱,所以我应该如何清理它,我还想知道如果可能的话,如何对伪代码进行措辞。

#open file with list
infile  = open("unsorted_fruits.txt", "r") 
#open file writing to
outfile = open("sorted_fruits.txt", "w")      
#create variable to work with list
all_lines = infile.readlines()              
for line in all_lines:                      
    print (line,)          

#this function has sorted other list
def insertion_sort(list):                   
    for index in range(1, len(list)):
        value = list[index]
        i = index - 1
        while i >= 0:
            if value < list[i]:
                list[i+1] = list[i]
                list[i] = value         
                i = i - 1               
            else:
                break  

#calling the function to sort 
insertion_sort(all_lines)                   
all_sorted = str(all_lines)                                                                  
#print list to show its sorted
print (all_sorted)
#write the sorted list to the file
outfile.write(all_sorted)                                    

infile.close()                              
outfile.close()
exit() 

Input:papaya 输入:木瓜

kiwifruit 奇异果

zapote blanco 扎波特·布兰科

huckleberry 哈克贝利

banana 香蕉

fig

lime 酸橙

xigua 西瓜

vanilla 香草

yiessas 伊耶萨斯

tamarind 罗望子

umkolo 乌姆科洛

quince

apple 苹果

imbu 因布

elderberry 接骨木浆果

juneberry 六月

mango 芒果

strawberry 草莓

nectarine 油桃

date 日期

cherry 樱桃

orange 橙子

watermelon 西瓜

grape 葡萄

raspberry 覆盆子

Output: ['\\n', '\\n', '\\n', '\\n', '\\n', '\\n', '\\n', '\\n', '\\n', '\\n', '\\n', '\\n', '\\n', '\\n', '\\n', '\\n', '\\n', '\\n', '\\n', '\\n', '\\n', '\\n', '\\n', '\\n', '\\n', 'apple\\n', 'banana\\n', 'cherry\\n', 'date\\n', 'elderberry\\n', 'fig\\n', 'grape\\n', 'huckleberry\\n', 'imbu\\n', 'juneberry\\n', 'kiwifruit\\n', 'lime\\n', 'mango\\n', 'nectarine\\n', 'orange\\n', 'papaya\\n', 'quince\\n', 'raspberry\\n', 'strawberry\\n', 'tamarind\\n', 'umkolo\\n', 'vanilla\\n', 'watermelon\\n', 'xigua\\n', 'yiessas\\n', 'zapote blanco\\n'] 输出:['\\ n','\\ n','\\ n','\\ n','\\ n','\\ n','\\ n','\\ n','\\ n','\\ n','\\ n','\\ n','\\ n','\\ n','\\ n','\\ n','\\ n','\\ n','\\ n','\\ n','\\ n','\\ n','\\ n','\\ n','\\ n','apple \\ n','banana \\ n','cherry \\ n','date \\ n ','接骨木果\\ n','无花果\\ n','葡萄\\ n','哈克贝利\\ n','imbu \\ n','juneberry \\ n','奇异果\\ n','石灰\\ n', '芒果\\ n','油桃\\ n','橙色\\ n','木瓜\\ n','木瓜\\ n','树莓\\ n','草莓\\ n','罗望子\\ n','umkolo \\ n','香草\\ n','西瓜\\ n','西瓜\\ n','yiessas \\ n','zapote blanco \\ n']

This is probably due to the file having extra newlines at the end of the file which are being picked up in the readlines() function. 这可能是由于文件末尾有额外的换行符,这些额外的换行符已在readlines()函数中获取。

When you go to print each item in your final list, just filter out those that are new lines only: 当您要打印最终列表中的每个项目时,只需过滤掉那些仅换行的项目即可:

for word in all_sorted:
    if word.rstrip('\n'):
        print(word.rstrip('\n'))

The rstrip() function (right-strip) strips all newlines at the end of a word. rstrip()函数(右移)在单词末尾rstrip()所有换行符。 If the word is only a new line, then rstrip will return an empty string, which is filtered out by the if statement. 如果单词只是换行符,则rstrip将返回一个空字符串,该字符串由if语句过滤掉。

It's not really the output that's the problem here. 问题出在这里,实际上不是输出。 It's the way you read the list of fruits. 这是您阅读水果清单的方式。 You really want to sort fruits , not lines . 您真的想对水果进行排序,而不是对进行排序。

Many of the lines in the input file are blank, and you don't want to include them. 输入文件中的许多行都是空白的,您不想包含它们。 And you probably don't really want to consider the trailing '\\n' as part of each fruit, either. 而且,您可能也不想将尾部的'\\ n'视为每个水果的一部分。

So instead of iterating through infile.readlines(), I recommend iterating through infile.read().splitlines(). 因此,我建议不要遍历infile.readlines(),而建议遍历infile.read()。splitlines()。 That will automatically strip the trailing \\n. 这将自动删除尾随\\ n。 And while you're at it, you can drop the blank lines. 当您使用它时,可以删除空白行。

with open('unsorted_fruits.txt', 'r') as infile:
    fruits = [f for f in infile.read().splitlines() if f != '']

Then you can sort fruits instead of lines. 然后,您可以对水果而非行进行排序。 And if you don't want then the final output to be written as the string representation of a Python list, you can use print(). 如果您不希望将最终输出写为Python列表的字符串表示形式,则可以使用print()。

for fruit in fruits:
    print(fruit, file=outfile)

Or file.writelines() 或file.writelines()

outfile.writelines(f + '\n' for f in fruits)

Now the output file looks like this using this code. 现在,使用此代码,输出文件如下所示。 Anyone have advice to make it look nicer. 任何人都建议使它看起来更好。 applebananacherrydateelderberryfiggrapehuckleberryimbujuneberrykiwifruitlimemangonectarineorangepapayaquinceraspberrystrawberrytamarindumkolovanillawatermelonxiguayiessaszapote blanco['\\n', '\\n', '\\n', '\\n', '\\n', '\\n', '\\n', '\\n', '\\n', '\\n', '\\n', '\\n', '\\n', '\\n', '\\n', '\\n', '\\n', '\\n', '\\n', '\\n', '\\n', '\\n', '\\n', '\\n', '\\n', 'apple\\n', 'banana\\n', 'cherry\\n', 'date\\n', 'elderberry\\n', 'fig\\n', 'grape\\n', 'huckleberry\\n', 'imbu\\n', 'juneberry\\n', 'kiwifruit\\n', 'lime\\n', 'mango\\n', 'nectarine\\n', 'orange\\n', 'papaya\\n', 'quince\\n', 'raspberry\\n', 'strawberry\\n', 'tamarind\\n', 'umkolo\\n', 'vanilla\\n', 'watermelon\\n', 'xigua\\n', 'yiessas\\n', 'zapote blanco\\n'] applebananacherrydateelderberryfiggrapehuckleberryimbujuneberrykiwifruitlimemangonectarineorangepapayaquinceraspberrystrawberrytamarindumkolovanillawatermelonxiguayiessaszapote blanco ['\\ n','\\ n','\\ n','\\ n','\\ n','\\ n',' n','\\ n','\\ n','\\ n','\\ n','\\ n','\\ n','\\ n','\\ n','\\ n','\\ n','\\ n','\\ n','\\ n','\\ n','\\ n','apple \\ n','banana \\ n','cherry \\ n','date \\ n ','接骨木果\\ n','无花果\\ n','葡萄\\ n','哈克贝利\\ n','imbu \\ n','juneberry \\ n','奇异果\\ n','石灰\\ n', '芒果\\ n','油桃\\ n','橙色\\ n','木瓜\\ n','木瓜\\ n','树莓\\ n','草莓\\ n','罗望子\\ n','umkolo \\ n','香草\\ n','西瓜\\ n','西瓜\\ n','yiessas \\ n','zapote blanco \\ n']

#open file with list
infile  = open("unsorted_fruits.txt", "r") 
#open file writing to
outfile = open("sorted_fruits.txt", "w")      
#create variable to work with list
all_lines = infile.readlines()              
for line in all_lines:                      
    print (line,)          

#this function has sorted other list
def insertion_sort(list):                   
    for index in range(1, len(list)):
        value = list[index]
        i = index - 1
        while i >= 0:
            if value < list[i]:
                list[i+1] = list[i]
                list[i] = value         
                i = i - 1               
            else:
                break  

#calling the function to sort and make it look nicer
insertion_sort(all_lines)
for word in all_lines:
    if word.rstrip('\n'):
        print(word.rstrip('\n'))
for word in all_lines:
    if word.rstrip('\n'):
       outfile.write(word.rstrip('\n'))

all_sorted = str(all_lines)

#write the sorted list to the file
outfile.write(all_sorted)                                    

infile.close()                              
outfile.close()
exit() 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM