【发布时间】:2020-02-01 03:50:12
【问题描述】:
我正在尝试使用 Python 3 删除括号和所有数据。
我研究了几个不同的主题,包括这里:
How to remove parentheses and all data within using Pandas/Python?
终于得到之后:
re.sub(r"\(.*\)|\s-\s.*", r"", str1)
为了运行没有错误,它没有从 str1 字符串中删除内容。
然后我尝试了这种方法:
How to remove text within parentheses from Python string?
在读取文件并存储到 str1 之前从文件中删除括号和内容 - 但我收到此错误:
Traceback (most recent call last):
File "sum_all.py", line 27, in <module>
data.append(line.replace(match.group(),'').strip())
AttributeError: 'NoneType' object has no attribute 'group'
这是代码,我显然是新手,感谢任何帮助!
# Python3 program to calculate sum of
# all numbers present in a str1ing
# containing alphanumeric characters
# Function to calculate sum of all
# numbers present in a str1ing
# containing alphanumeric characters
import re
import math
import pyperclip
import pandas
def find_sum(str1):
# Regular Expression that matches digits in between a string
return sum(map(int,re.findall('\d+',str1)))
def find_sum2(str2):
# Regular Expression that matches digits where hr follows short for hours
return sum(map(int,re.findall('(\d+)hr',str1)))
str2=0
# Regular Expression
data=[]
pattern=r'\(.+\)|\s\-.+'
with open('project.txt','r') as f:
for line in f:
match=re.search(pattern,line)
data.append(line.replace(match.group(),'').strip())
print(data)
# input alphanumeric str1ing
with open ("project.txt", "r") as myfile:
str1=myfile.read().replace('\n', '')
# Regular Expression that removes (*) and Normalizes White Space - didn't work
#re.sub(r"\(.*\)|\s-\s.*", r"", str1)
# Regular Expression that removes (*) - didn't work
#re.sub(r"\(.*\)", r"", str1)
【问题讨论】:
标签: regex python-3.x