我有下面的脚本基本上删除了“ - ”之后的句子,当announce.txt包含下面的输入因为它有多个“ - ”时它正在打破,我基本上想要根据第一个“ - ”拆分最后一点......请 建议如何做到这一点...我有预期的输出
INPUT: - //components/rel/bt.wcnss/2.4/wcnss_proc/bt/platform/rom/inc/oi_sbc_tables-generated.h#1 - 分支变更700801(文字)
预期输出: - //components/rel/bt.wcnss/2.4/wcnss_proc/bt/platform/rom/inc/oi_sbc_tables-generated.h#1
f = open('announce.txt', 'r')
z = f.readlines()
f.close()
k = []
for items in z:
print 'Current item %s'%items
answer = items.split('-');
k.append(answer[0].strip() + '\n')
f2 = open('foobar4.txt', 'w')
f2.writelines(k)
f2.close()
答案 0 :(得分:1)
rfind
是你的朋友。
>>> input = '- //components/rel/bt.wcnss/2.4/wcnss_proc/bt/platform/rom/inc/oi_sbc_tables-generated.h#1 - branch change 700801 (text)'
>>> output = input[:input.rfind('-')]
>>> print output
- //components/rel/bt.wcnss/2.4/wcnss_proc/bt/platform/rom/inc/oi_sbc_tables-generated.h#1
已知错误:
tables-generated
)input[:-1]
)答案 1 :(得分:1)
贪婪的RegEx怎么样:
import re
original_string = u'//components/rel/bt.wcnss/2.4/wcnss_proc/bt/platform/rom/inc/oi_sbc_tables-generated.h#1 - branch change 700801 (text)'
match = re.match(r'(.*)-', original_string).groups()
if match:
new_string = match.groups()[0]
答案 2 :(得分:1)
"a-b-c-d".rsplit('-',1)
>>> ['a-b-c', 'd']
-
items = '- //components/rel/bt.wcnss/2.4/wcnss_proc/bt/platform/rom/inc/oi_sbc_tables-generated.h#1 - branch change 700801 (text)'
answer = items.rsplit('-',1);
k.append(answer[0].strip() + '\n')
# print answer[0].strip()