从Python中的现有文件中选择一些单词 [英] Select some words from an existing file in Python
本文介绍了从Python中的现有文件中选择一些单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用'endswith'分隔以某个字符串结尾的文本文件( text.txt )的确切单词.事实是我的变量
I want to separate the exact words of a text file (text.txt) ending in a certain string by using 'endswith'. The fact is that my variable
h=[w for w in 'text.txt' if w.endswith('os')]
在我打电话时没有给出我想要的东西.另一方面,如果我尝试命名打开的文件
does not give what I want when I call it. On the other hand, if I try naming the open file
f=open('text.txt')
h=[w for w in f if w.endswith('os')]
也不起作用.我应该先将文本转换为列表吗?
does not work either. Should I convert the text into a list first?
Comment: I hope this is not duplicate. It is not the same as this former question although close to it.
推荐答案
首先打开文件,然后按以下方式对其进行处理:
Open the file first and then process it like this:
with open('text.txt', 'r') as file:
content = file.read()
h=[w for w in content.split() if w.endswith('os')]
这篇关于从Python中的现有文件中选择一些单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文