将文本放在一对括号内,但不能放在双方括号内

2024-10-02 20:39:46 发布

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

  1. 在下面的文字中我只想得到“七月四日”

Hello, happy [4th of July]. I love the [[firework]]

  1. 我有这些文字:

    text = {{Hey, how are you.}} I've watched John Mulaney all night. [[Category: Comedy]] [[Image: John Mulaney]]

我正在尝试删除{{嘿,你好。}}、[[类别:喜剧]]和[[图片:约翰穆拉尼]]。这是我迄今为止尝试过的,但似乎不起作用:

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)

Tags: textimagereyouhellojohnarehow
3条回答

你在用一种很奇怪的方式去做那件事。尝试阅读有关正则表达式文档的更多信息。请尝试以下操作:

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个空格。我让你想想怎么做。有帮助吗?你知道吗

请看一下关于如何使用RE排除除[7月4日]以外的所有内容的文档。你知道吗

@Duy,看下面两个例子。你知道吗

I've used the concept of list comprehension & string's split() method.

### 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']
>>>

例2

>>> 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']
>>>

下面的代码是您的第二个输入文本。你知道吗

例3

>>> 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]]']
>>>
# 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.

相关问题 更多 >