[英]Python: how to generate a list of words from a string and save it in a text file according to their index?
with open('filename.txt', "r") as word_list:
words = word_list.read().split('')
with open("file.txt", "w") as output:
output.write(str(words))
But the output is not in order (I want one word per line) as I want them to be.但是 output 不符合我的要求(我希望每行一个字)。 My apology: I am a very beginner in python.我的道歉:我是 python 的初学者。 Thanks in advance if anyone can figure out how I can sort words using python according to the index from the list.如果有人能根据列表中的索引弄清楚我如何使用 python 对单词进行排序,请提前致谢。
Something like this might work:像这样的东西可能会起作用:
with open('filename.txt', "r") as word_list:
words = word_list.read().split(' ')
with open("file.txt", "w") as output:
for index, word in enumerate(words):
output.write(f'{index}. {word}\n')
The code uses the built-in enumerate function to loop through the list of words with an index (0-based).该代码使用内置枚举function 循环遍历具有索引(从 0 开始)的单词列表。 It also uses string interpolation (so called f-strings ) to build the correct output string.它还使用字符串插值(所谓的 f-strings )来构建正确的 output 字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.