我可以在正则表达式中插入变量吗?
Can I insert variables in Regular Expression?
我想用正则表达式从文本中获取具体信息,我举了一个半伪代码的例子~你也可以用半伪代码回复我:
list=["orange","green","grey"]
text= "The Orange is orange"
for word in list:
if word == re.compile(r'word, text):
capture Orange in order to have the noun
小心!我的问题集中在是否有可能使用 variables (如上面的 word )以便进行循环并查看是否有相同的单词在基于列表的文本中。
不关注橙子怎么抢
我认为 Biffen 的想法是正确的,如果您将其用于 POS 标记,您将陷入痛苦的世界。无论如何,这允许您匹配 text
变量
中的单词
for word in list:
if word in text:
# Do what you want with word
如果您想使用正则表达式,那么您可以从字符串构建模式,使用括号进行捕获。然后使用 group()
访问捕获的模式
for word in list:
pattern = re.compile(".*(" + word + ").*")
m = re.match(pattern, text)
if m:
print(m.group(1))
我想用正则表达式从文本中获取具体信息,我举了一个半伪代码的例子~你也可以用半伪代码回复我:
list=["orange","green","grey"]
text= "The Orange is orange"
for word in list:
if word == re.compile(r'word, text):
capture Orange in order to have the noun
小心!我的问题集中在是否有可能使用 variables (如上面的 word )以便进行循环并查看是否有相同的单词在基于列表的文本中。
不关注橙子怎么抢
我认为 Biffen 的想法是正确的,如果您将其用于 POS 标记,您将陷入痛苦的世界。无论如何,这允许您匹配 text
变量
for word in list:
if word in text:
# Do what you want with word
如果您想使用正则表达式,那么您可以从字符串构建模式,使用括号进行捕获。然后使用 group()
访问捕获的模式
for word in list:
pattern = re.compile(".*(" + word + ").*")
m = re.match(pattern, text)
if m:
print(m.group(1))