在 python 中找到特定的词并在该词之后阅读

find specific word and read after that word in python

所以我对 python 非常陌生。 需要一些基本的帮助。

我的逻辑是在文本文件中查找单词。

party A %aapple 1
Party B %bat 2
Party C c 3

我需要找到所有以 % 开头的单词。

我的密码是

 searchfile = open("text.txt", "r")
for line in searchfile:
 for char in line:
if "%" in char:
    print char      

searchfile.close()

但输出只有 % 字符。我需要 putput 是 %apple 和 %bat

有什么帮助吗?

您没有正确读取文件。

searchfile = open("text.txt", "r")

lines = [line.strip() for line in searchfile.readlines()]
for line in lines:
    for word in line.split(" "):
        if word.startswith("%"):
            print word

searchfile.close()

您还应该探索正则表达式来解决这个问题。

为了举例说明,我正在跟进 Bipul Jain 关于展示如何使用正则表达式完成此操作的建议:

import re

with open('text.txt', 'r') as f:
    file = f.read()

re.findall(r'%\w+', file)

结果:

['%apple', '%bat']