我有一个包含多行的文件,如下所示:
'AMS_Investigation|txtt.co_BigtittedBlondOtherNight_1371078139195_+14155186442', {'cf:rv': '0'}
我想用另一个号码替换 1371078139195(在这种情况下)。我要替换的值始终位于第一个逗号分隔的单词中,并且始终是该单词中倒数第二个下划线分隔的值。以下是我这样做的方式并且它有效,但这似乎不合时宜且笨拙。
>>> line="'AMS_Investigation|txtt.co_BigtittedBlondOtherNight_1371078139195_+14155186442', {'cf:rv': '0'}"
>>> l1=",".join(line.split(",")[1:])
>>> print l1
{'cf:rv': '0'}
>>> l2=line.split(",")[0]
>>> print l2
'AMS_Investigation|txtt.co_BigtittedBlondOtherNight_1371078139195_+14155186442'
>>> print "_".join(l2.split('_')[:-2])
'AMS_Investigation|txtt.co_BigtittedBlondOtherNight
>>>
>>> print "_".join(l2.split('_')[:-2])+ "_1234567_"+(l2.split('_')[-1])
'AMS_Investigation|txtt.co_BigtittedBlondOtherNight_1234567_+14155186442'
>>> print "_".join(l2.split('_')[:-2])+ "_1234567_"+(l2.split('_')[-1]) + "," + l1
'AMS_Investigation|txtt.co_BigtittedBlondOtherNight_1234567_+14155186442', {'cf:rv': '0'}
>>>
是否有更简单的方法来替换(可能使用正则表达式)该值?我无法想象这是最好的方法
我有几个答案,我必须强调它是倒数第二个强调值。以下是有效的字符串:
line = "'AMS_Investigation|txtt.co_23456_BigtittedBlondOtherNight_1371078139195_+14155186442', {'cf:rv': '0'}"
line = "'AMS_Investigation|txtt.co_23456_BigtittedBlondOtherNight_1371078139195_14155186442', {'cf:rv': '0'}"
line = "'AMS_Investigation|txtt.co_1371078139195_BigtittedBlondOtherNight_1371078139195_1371078139195', {'cf:rv': '0'}"
在上述情况下,字符串中有一个数字字符串不在倒数第二个下划线之后。最后一部分可能是也可能不是全数字(可能是+14155186442,也可能是14155186442)。对不起,我没有在上面提到这一点。
一个