Hello, happy [4th of July]. I love the [[firework]]
我有这些文字:
text = {{嘿,你好。}}我整夜都在看约翰·穆拉尼。 [[类别:喜剧]] [[图片:约翰·穆拉尼]]
我正在尝试删除{{嘿,你怎么样。}},[[类别:喜剧]]和[[图片:约翰·穆拉尼]]。到目前为止,这是我尝试过的方法,但似乎不起作用:
hey_how_are_you = re.compile('\{\{.*\}\}')
category = re.compile('\[\[Category:.*?\]\]')
image = re.compile('\[\[Image:.*?\]\]')
text = hey_how_are_you.sub('', text)
text = category.sub('', text)
text = image.sub('', text)
答案 0 :(得分:2)
# 1.
text="Hello, happy [4th of July]. I love the [[firework]]. "
l=re.findall(r"(?<!\[)\[([^\[\]]+)\]",text)
print(l,"\n",l[0])
# 2.
text2=" {{Hey, how are you.}} I've watched John Mulaney all night. [[Category: Comedy]] [[Image: John Mulaney]]"
print(re.sub(r"\{\{.*?\}\}|\[\[\s*Category:.*?\]\]|\[\[\s*Image:.*?\]\]","",text2))
Output:
['4th of July']
4th of July
I've watched John Mulaney all night.
In the 1st problem you can use negative lookbehind: (?<!\[)
Your regexp in the 2nd problem works for me. (What error you have?) However, it can be solved in one pass, too.
答案 1 :(得分:1)
您正在以一种非常奇怪的方式进行操作。尝试阅读更多有关正则表达式文档的内容。尝试以下方法:
import re
text = "{{Hey, how are you.}} I've watched John Mulaney all night. [[Category: Comedy]] [[Image: John Mulaney]]"
text = re.sub('\{\{.*\}\}', '', text)
text = re.sub('\[\[Category:.*?\]\]', '', text)
text = re.sub('\[\[Image:.*?\]\]', '',text)
text
Out[ ]:
" I've watched John Mulaney all night. "
请注意,输出字符串的前面还有2个空格。我会让你想办法。有帮助吗?
P.S。查看有关如何使用RE排除[7月4日]以外的所有内容的文档。
答案 2 :(得分:0)
@Duy ,请看以下两个示例。
我使用了列表理解和字符串的 split()方法的概念。
### Example 1
>>> string = 'Hello, happy [4th of July]. I love the [[firework]]'
>>>
>>> part1 = string.split('[')
>>> part1
['Hello, happy ', '4th of July]. I love the ', '', 'firework]]']
>>>
>>> part2 = [s[:s.index(']')] for s in part1 if ']' in s and not ']]' in s]
>>> part2
['4th of July']
>>>
>>> sentence1 = "This is [Great opportunity] to [[learn]] [Nice things] and [Programming] [[One]] of them]."
>>> part1 = sentence1.split('[')
>>> part2 = [s[:s.index(']')] for s in part1 if ']' in s and not ']]' in s]
>>> part2
['Great opportunity', 'Nice things', 'Programming']
>>>
下面的代码是您的第二个输入文本。
>>> import re
>>>
>>> string2 = "text = {{Hey, how are you.}} I've watched John Mulaney all night. [[Category: Comedy]] [[Image: John Mulaney]]"
>>>
>>> part1 = re.split('[\{\[]', string2)
>>> part1
['text = ', '', "Hey, how are you.}} I've watched John Mulaney all night. ", '', 'Category: Comedy]] ', '', 'Image: John Mulaney]]']
>>> part3 = [ "[["+ s[:s.index(']]') + 2] if ']]' in s else "{{" + s[:s.index('}}') + 2] for s in part1 if ']]' in s or '}}' in s]
>>>
>>> part3
['{{Hey, how are you.}}', '[[Category: Comedy]]', '[[Image: John Mulaney]]']
>>>