【问题标题】:Want to read words from txt file and insert that word in a list (p_words) which have character 'p' in it [closed]想要从文本文件中读取单词并将该单词插入其中包含字符“p”的列表(p 个单词)中 [关闭]
【发布时间】:2019-06-08 12:32:22
【问题描述】:
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) 中

【问题讨论】:

  • 这似乎是一个家庭作业问题,您根本没有尝试完成任务。

标签: python python-3.x list for-loop


【解决方案1】:

您需要第二个循环来查看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)

您可能对if 'p' in value: 而不是if value.startswith('p'): 感兴趣,以防您真的在寻找其中包含“p”的单词,而不是仅以“p”开头的单词。

【讨论】:

  • 我需要所有包含字符 p 的单词
猜你喜欢
  • 1970-01-01
  • 2011-04-12
  • 2020-06-25
  • 2016-08-10
  • 1970-01-01
  • 2020-06-24
  • 2012-09-23
  • 1970-01-01
  • 2021-10-12
相关资源
最近更新 更多