2017-12-27 1503 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) 
相关问题