0

我有一组记录,例如:

姓名

  • 姓名保罗·贝瑞:现在
  • 地址乔治·内基:不存在
  • 姓名鲍勃·范巴斯滕:现在
  • 姓名 Richard Von Rumpy:不存在
  • 名字爸爸徽章:不存在
  • 姓名保罗·贝瑞:现在
  • Street George Necky:不存在
  • 街头鲍勃·范巴斯滕:现在
  • 姓名 Richard Von Rumpy:不存在
  • 城市爸爸徽章:不存在

我希望所有以Name开头的记录都采用这种形式

  • 姓名姓名 姓: 不存在

以其他词开头的记录保持原样。

即我想将字符串“not”添加到以Name开头的记录中,但它不是。我正在使用 python (pywikipediabot)

python replace.py -dotall -regex 'Name ((?!not ).*?)present' 'Name \1not present'

但即使它已经存在,它也会添加“不”。

也许我还没有理解否定的前瞻语法?

4

3 回答 3

2

只需查找: present并将其替换为: not present.

编辑:改进的答案:

for line in lines:
    m = re.match('^Name[^:]*: present', line)
    if m:
        print re.sub(': present', ': not present', line)
    else:
       print line
于 2012-03-01T08:31:44.177 回答
0

以下将做到这一点:

re.sub(r'(Name.*?)(not )?present$', r'\1not present', s)
于 2012-03-01T08:33:48.237 回答
0

你需要一个“消极的后视”表达。这种替换将起作用:

'Name (.*)(?<!not )present' -> 'Name \1not present'

.* 匹配 "Name" 和 "present" 之间的所有内容,但只有当 "present" 前面没有 "not" 时,整个正则表达式才匹配。

你确定你需要-dotall吗?看起来您只想一行内.*匹配。

于 2012-03-01T10:17:39.873 回答