首页 > 解决方案 > 想要从 txt 文件中读取单词并将该单词插入到包含字符“p”的列表 (p_words) 中

问题描述

with open("school_prompt.txt" , "r") as word:
p_words = []
for w in word.readlines():
    value = w.split(' ')
    if value.startswith('p'):
        p_words.append(value)
print(p_words)

想要从 txt 文件中读取单词并将该单词插入到包含字符“p”的列表 (p_words) 中

标签: pythonpython-3.xlistfor-loop

解决方案


您需要第二个循环来查看 的内容split,这将生成一个对象列表,例如:

with open("school_prompt.txt" , "r") as word:
p_words = []
for w in word.readlines():
    for value in w.split(' '):
        if value.startswith('p'):
            p_words.append(value)
print(p_words)

如果您真的在寻找包含“p”的单词,而不是仅在开头包含“p”,您可能会选择性地对if 'p' in value:ranther than感兴趣。if value.startswith('p'):


推荐阅读