简体   繁体   English

Python:如何从字符串中生成单词列表并根据其索引将其保存在文本文件中?

[英]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.

相关问题 在Python中,如何根据列表删除字符串中的某些单词? - In Python, how to delete some words in a string according to a list? 如何在Python中从JSON文件生成索引列表? - How to generate an index list from a JSON file in Python? 如何从python中的文本文件返回单词列表 - How to return a list of words from a text file in python 使用 Python 从 .txt 文件中随机生成加权词列表 - Generate a list of weighted words from a .txt file randomly with Python Python:如何将列表中的文本+元素保存到txt文件 - Python: how to save text + element from the list to the txt file Python-匹配现有文本文件中存在的字符串列表 - Python - To match a list of string words present in a existing text file 如何在Python中从文本文件中排序单词 - How order words from a text file in Python 将元组列表(来自 itertools)转换为文本文件中的单词列表,Python - Convert a list of tuples (from itertools) into a list of words in a text file, Python 如何从python中的给定字符串生成1、2和3个单词的所有后续组合? - How to generate all subsequent combinations of 1, 2 and 3 words from a given string in python? python中如何将字符串转换为列表,从文本文件中读取字符串 - How to convert a string to list in python, the string is read from a text file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM