用python对文本文件中的内容进行排序
我读了一个文本文件。内容,我删除标点符号,全部改为小写,最后,我在一个新行上打印每个单词。但我现在遇到的问题是按字母顺序排序这些内容,之后我将保存在一个新的文本文件中。现在,我无法使用(排序方法),每次输入.method-accessifier时,排序方法都不怎么样。所以我的问题是,在我之前所做的早期文本操作之后,我如何按字母顺序对它们进行排序?用python对文本文件中的内容进行排序
punctuations = '''!()-[]{};:'"\,<>./[email protected]#$%^&*_~'''
no_punct = ""
#Open file
file = "research.txt"
f = open(file , 'r+')
#read file
contentOfFile = f.read()
#Remove punctuations from file content
for char in contentOfFile:
if char not in punctuations:
no_punct = (no_punct + char)
#print "Output of formatted document is"
for word in no_punct.lower().split():
print word
随着上述和后续的帮助,我终于能够实现里程碑。但是我注意到,如果我在控制台上打印,它会打印出来,但是当我尝试创建新文件并将文字保存为显示在控制台上时,这些文字在保存到新文件时没有格式化。但是,所有的单词都保存在一条长长的直线上。在创建名为“newFile.txt”的新文本文件后,我添加了nf.write(word)。我认为这会自动将每个单词添加到textFile格式和每个新行。这是错的吗?谢谢。
punctuations = '''!()-[]{};:'"\,<>./[email protected]#$%^&*_~'''
no_punct = ""
#Open file
file = "research.txt"
f = open(file , 'r+')
#read file
contentOfFile = f.read()
#Remove punctuations from file content
for char in contentOfFile:
if char not in punctuations:
no_punct = (no_punct + char)
#create new file to save formatted words to
newFile = "newFile.txt"
nf = open(newFile , 'w+')
#write words to the new textFile
for word in sorted(no_punct.lower().split()):
nf.write(word)
#print word
你可以使用sorted
:
for word in sorted(no_punct.lower().split()):
print word
如果你想要的结果写入由线文件中的行,你可以试试这个:
with open("newFile.txt", "w") as f:
for word in sorted(no_punct.lower().split()):
f.write(word + os.linesep)
当然,你需要添加import os
在您的文件的开头,以便找到换行符os.linesep
。
非常感谢。这对我来说工作得很好。 – user3761841
非常感谢.... – user3761841
并将这个新的排序文字保存到文本文件?我该如何解决它?我刚刚使用这种格式'f = open(“newText.txt”,“w”)' – user3761841
word_in_file = no_punct.lower().split()
word_in_file.sort()
这是否对你的工作?
看着我的分数,我认为答案是否定的:p什么不行? – rmeertens
其实它确实。我使用了上面用户的答案。你的确按字母顺序打印出来,但要求每个单词都必须打印在新的一行上。但是那说,你的工作很好。谢谢... – user3761841
@ZdaR,你是什么意思的排序(列表)?没有'排序'内置功能。 –
是否要按字母顺序对每个单词或每行进行排序? –
感谢您的回复。对不起,我的解释不是很清楚。虽然,我的问题得到了答案@pschill – user3761841