python - 想要从 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) 中
解决方案
您需要第二个循环来查看 的内容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'):
推荐阅读
- numberformatexception - 自定义 OpenCsv CsvToBeanBuilder
- java - 使用休眠当前会话执行存储过程后无法执行任何读/写操作
- javascript - 如何设置 jest 以测试画布
- maven - Maven surefire 插件套件XmlFile 并行执行
- python - Python中如何提高基于Caffe的人脸检测模型的性能?
- javascript - 如何在 javaScript 中创建具有用户定义名称的对象?
- html - NetSuite 中带有 XML 的 IF 语句
- ios - 当 iPhone 设备进入 iBeacon 范围时广播弹出消息
- java - 如何在Android Q中检测拨出电话号码
- ionic-framework - Cordova 相机插件