我希望在Python中使用正则表达式来读取文本,找到其中情感>标记存在于<位置>标记相同句子中的所有实例,然后允许这些句子打印到输出文件的独特行:Python正则表达式扼流器 n
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()
麻烦的是,如果我在包含换行符文件读取,正则表达式失败:
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()
有什么办法来修改这个正则表达式等等当它撞击时它不会窒息\ n吗?我会非常感谢别人可以借用这个问题的任何建议。
在应用正则表达式之前,将文件读取为行或删除换行符。 – Andenthal