2017-12-27 1541 views
-1

我想刪除括號和駐留在這些括號中的文本以及連字符。一些字符串示例如下所示:
example = 'Year 1.2 Q4.1 (Section 1.5 Report (#222))'
example2 = 'Year 2-7 Q4.8 - Data markets and phases' ##there are two hyphens如何從Python字符串中刪除括號內的文本?

我想結果是:

example = 'Year 1.2 Q4.1' 
example2 = 'Year 2-7 Q4.8' 

如何刪除文本居住之中或之後的括號內的特殊字符?我只能找到str.strip()方法。我是Python的新手,所以任何反饋都非常感謝!

+2

方法有很多種。你應該看看用正則表達式來做。我用正則表達式標記它,很快正則表達式鯊魚將在這裏。 –

+1

[Python:按分隔符列表拆分字符串]的可能重複(https://stackoverflow.com/questions/4697006/python-split-string-by-list-of-separators) – splash58

+1

@AntonvBR lol。正則表達式的鯊魚正在水中盤旋 –

回答

5

您可以使用下面的正則表達式來得到期望的結果:

"\(.*\)|\s-\s.*" 
# ^ ^Pattern 2: everything followed by space, '-' hyphen, space 
# ^ Pattern 1: everything within brackets (....) 

採樣運行:

>>> import re 
>>> my_regex = "\(.*\)|\s-\s.*" 

>>> example = 'Year 1.2 Q4.1 (Section 1.5 Report (#222))' 
>>> example2 = 'Year 2-7 Q4.8 - Data markets and phases' 

>>> re.sub(my_regex, "", example) 
'Year 1.2 Q4.1' 
>>> re.sub(my_regex, "", example2) 
'Year 2-7 Q4.8' 

這裏我使用re.sub(pattern, repl, string, ...)其作爲文件說:

返回通過替換最左邊不重疊的 字符串中出現的模式替換repl。如果未找到 模式,則字符串將以未更改的形式返回。 repl可以是一個 字符串或函數;如果它是一個字符串,則處理其中的任何反斜槓轉義 。

0

這裏是沒有正則表達式的例子(只是爲了顯示你有很好的正則表達式即可):

的代碼添加串直到字符串Q開始:

example = 'Year 1.2 Q4.1 (Section 1.5 Report (#222))' 

def clean_string(s): 
    for item in s.split(): 
     yield item 
     if item.startswith('Q'): 
      break 

print(' '.join(clean_string(example))) 
1

我們可以做到這一點使用*和一次性變量。

example = 'Year 1.2 Q4.1 (Section 1.5 Report (#222))' 
display,*_ = example.split('(') 
print(display) 

example2 = 'Year 2-7 Q4.8 - Data markets and phases' ##there are two hyphens 
part_1,part_2,*_ = example2.split('-') 
display = part_1 + '-'+ part_2 
print(display) 
1

你可以嘗試這樣的事情,你需要很少的數據清洗你取結果後,使其爲您所需的輸出:

import re 
data=[] 
pattern=r'\(.+\)|\s\-.+' 
with open('file.txt','r') as f: 
    for line in f: 
     match=re.search(pattern,line) 
     data.append(line.replace(match.group(),'').strip()) 

print(data) 
相關問題