如何从txt文件中查找字符串,然后在python中打印下一个字符串

时间:2017-04-13 07:46:37

标签: python string

任何人都可以告诉我如何从文本文件中找到字符串或单词,然后打印下一个元素 f = open(“E:Test.txt”,“r”)  如果'感觉'在f:     打印( '真')

1 个答案:

答案 0 :(得分:0)

正则表达式可能是最好的选择。 我的简短测试文件包含以下内容: feel different

对于python 2.4:

>>> import re
>>> match_pattern = r'(<=?\bfeel\b)\s+\w+\b'
>>> f=open('E:Test.txt','r')
>>> ftext=f.read()
>>> f.close()
>>> [found.strip() for found in re.findall(match_pattern, ftext)]
['different']

对于python 2.7以上版本:

>>> import re
>>> match_pattern = r'(<=?\bfeel\b)\s+\w+\b'
>>> with open('E:Test.txt','r') as f:
>>>     ftext=f.read()
>>> [found.strip() for found in re.findall(match_pattern, ftext)]
['different']

这个正则表达式代替了&#34;感觉&#34;并返回任何空格加下一个单词。然后我们从所有返回的结果中删除该空格。