0

I have a .txt file in which the content are of this type:

DIRN straight-2
FOR minutes-5
DO crossing-6
WHAT Hall-7-13
DO take-10
WHAT Hall-3-15

What I want is another .txt file that can be generated with the help of python which will have this as its final content:

DIRN straight
FOR minutes
DO crossing
WHAT Hall-7
DO take
WHAT Hall-3

ie, I want to remove everything that comes after the last hyphen "-" in each line including hyphen also.

Please help me with the python code and thanks for any help in advance.

4

1 回答 1

7

在 Python 2 或 3 中,这有效:

s='''DIRN straight-2
FOR minutes-5
DO crossing-6
WHAT Hall-7-13
DO take-10
WHAT Hall-3-15'''

import re

for line in s.splitlines():
    line=re.sub(r'^(.*)-\d+$',r'\1',line)
    print line

您可以通过这种方式在 Python 中执行非正则表达式:

for line in s.splitlines():
    line=line.rpartition('-')[0] if '-' in line else line
    print(line)

或者 - 可能更好:

for line in s.splitlines():
    line=line[:line.rindex("-")] if '-' in line else line    
    print line

正则表达式更具体,因为它只匹配-\d+字符串的末尾。

任何情况下,打印:

DIRN straight
FOR minutes
DO crossing
WHAT Hall-7
DO take
WHAT Hall-3
于 2013-03-18T22:18:34.913 回答