举个例子,我有一个utf-8字典文本文件,如下所示:
iguanodont
primer
blindfolder
pseudosperm
chanciest
givers
renascent
lecanine
struth
unionizers
autoriser
interpunctuation
monophylies
approximativeness
我需要遍历,将每五行分组在一起(用空格分隔),然后吐出一个新的文本文件,如下所示:
iguanodont primer blindfolder pseudosperm chanciest
givers renascent lecanine struth unionizers
autoriser interpunctuation monophylies approximativeness
到目前为止,我有这个。我是新来的,很抱歉这太平庸了。先谢谢你。你知道吗
import io
dictionary = io.open("shuffled.txt", 'r')
不完全是你想要的,但相似。这将生成分组数据列表,然后将其转换为字符串并保存到文件中。你知道吗
输出:
[['iguanodont'、'primer'、'blindfolder'、'pseudomer'、'chanciest']、['givers'、'renasant'、'lecanine'、'struth'、'unionizers']、['autoriser'、'interpuncutation'、'monophylies'、'approximativersity'、'、'']]
除非您的输入文件太大,无法放入内存,否则将其读入一个列表并切片该列表是最简单的——3行左右:
当然,处理无界文件、在异常情况下确保关闭等等,您可能会变得更喜欢,但最好在可行的情况下保持简单,并且只有在保证的情况下才增加复杂性。你知道吗
相关问题 更多 >
编程相关推荐