Python正则表达式阻塞\n
我希望使用Python中的正则表达式读取文本,查找Python正则表达式阻塞\n,python,regex,search,line-breaks,proximity,Python,Regex,Search,Line Breaks,Proximity,我希望使用Python中的正则表达式读取文本,查找标记与标记位于同一句子中的所有实例,然后允许将这些句子打印到输出文件的唯一行: import re out = open('out.txt', 'w') readfile = "<location> Oklahoma </location> where the wind comes <emotion> sweeping </emotion> down <location> the pl
import re
out = open('out.txt', 'w')
readfile = "<location> Oklahoma </location> where the wind comes <emotion> sweeping </emotion> down <location> the plain </location>. And the waving wheat. It can sure smell <emotion> sweet </emotion>."
for match in re.findall(r'(?:(?<=\.)\s+|^)((?=(?:(?!\.(?:\s|$)).)*?\bemotion>(?=\s|\.|$))(?=(?:(?!\.(?:\s|$)).)*?\blocation>(?=\s|\.|$)).*?\.(?=\s|$))', readfile, flags=re.I):
line = ''.join(str(x) for x in match)
out.write(line + '\n')
out.close()
重新导入
out=open('out.txt','w')
readfile=“俄克拉何马州,那里的风席卷着平原。还有飘动的小麦。它闻起来确实很香。”
对于re.findall中的匹配(r'(?:(?=\s |.$)(?=(?:(?!\)(?:\s |$)*?\blocation>(?=\s | |.$).*(?=\s | |$)”,readfile,flags=re.I):
行=“”。连接(str(x)表示匹配中的x)
out.write(第+'\n'行)
结束
问题在于,如果我读入一个包含换行符的文件,正则表达式将失败:
import re
out = open('out.txt', 'w')
readfile = "<location> Oklahoma </location> where the wind \n comes <emotion> sweeping </emotion> down <location> the plain </location>. And the waving wheat. It can sure smell <emotion> sweet </emotion>."
for match in re.findall(r'(?:(?<=\.)\s+|^)((?=(?:(?!\.(?:\s|$)).)*?\bemotion>(?=\s|\.|$))(?=(?:(?!\.(?:\s|$)).)*?\blocation>(?=\s|\.|$)).*?\.(?=\s|$))', readfile, flags=re.I):
line = ''.join(str(x) for x in match)
out.write(line + '\n')
out.close()
重新导入
out=open('out.txt','w')
readfile=“俄克拉何马州,那里的风\n横扫平原。还有飘动的小麦。它闻起来确实很香。”
对于re.findall中的匹配(r'(?:(?=\s |.$)(?=(?:(?!\)(?:\s |$)*?\blocation>(?=\s | |.$).*(?=\s | |$)”,readfile,flags=re.I):
行=“”。连接(str(x)表示匹配中的x)
out.write(第+'\n'行)
结束
是否有任何方法修改此正则表达式,使其在命中时不会阻塞\n?如果其他人能就这个问题提供任何建议,我将不胜感激。使用
re.DOTALL
/re.S
flags = re.DOTALL | re.I
将re(它们是相同的东西)添加到正则表达式中的标志中。这将导致
也匹配换行符。因此,flags
参数的新值将是re.I | re.S
或者将文件作为行读取,或者在应用正则表达式之前去掉换行符。谢谢你,F.J!谢谢你的解释!