“成对词提取器”正则表达式

2024-05-23 19:47:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Python中使用正则表达式来提取“And”单词。意思,用和隔开的词。你知道吗

例如

  • 银行与金融
  • 损益

迄今为止的努力:

import re
read = open("sample.txt", "r")
regex = re.compile('(?:\S+\s)?\S*and\S*(?:\s\S+)?')
f=open('write.txt','w')
for line in read:
    words = regex.findall(line)
    for word in words:
        f.write(str(word)+'\n')
f.close()

这段代码似乎工作得很好,但可以在命令之类的词中找到和。你知道吗

所以我用了这个正则表达式

regex = re.compile('a-zA-Z]+\s?\S*and\S*\s+[a-zA-Z]+')

它在网站中运行良好,但在python中只返回单词,不返回前面的单词和后面的单词作为输出。你知道吗

我的目的是在一个文档中找到被分隔开的单词。你知道吗

输入

This is a sample text to find profit and loss. It should also find banking and finance. But it should not find commands.

电流输出

  • 损益。你知道吗
  • 银行和金融。你知道吗
  • 查找命令。你知道吗

预计产量

  • 损益
  • 银行与金融

Tags: andsampleretxtforread银行open
2条回答

你可以试试这个:

\w+(?=\sand\s)|(?<=\sand\s)\w+

即:

  • 一些单词(\w+)只在它前面的地方匹配了一个肯定的前瞻断言,或者
  • 一些work(\w+)只在\sAnd\s之后匹配,并且在断言后面有一个积极的外观

正lookback需要一个固定长度的字符串,因此您不能执行(?<=\s+and\s+),因此此解决方案假设所有间距都是单个空格。你知道吗

Tested在regex101.com

enter image description here

编辑

关于问题中的更新,您可以尝试将某物某物作为一个三字短语:

\w+(?:\s+and\s+)\w+

Tested此输出:

enter image description here

你把事情弄得更复杂了。只需使用以下正则表达式:

\S+\sand\s\S+

See it in action

问题是您在and周围添加的\S*。它匹配“and”周围任意数量的非空白字符,这将匹配“brandy”之类的词。你知道吗

相关问题 更多 >