目前您正在将文件的前三行分配给name
,weeks_worked
和weekly_payment
. 但是你想要的(我认为)是分隔一行,格式为('larry', 3, 100)
(每个文件只有一行吗?)。
所以你可能想要这样的代码:
from re import compile
# your code to choose file
line_format = compile(r"\s*\(\s*'([^']*)'\s*,\s*(\d+)\s*,\s*(\d+)\s*\)")
file = open(emp_choice + ".txt")
line = file.readline() # read the first line only
match = line_format.match(line)
if match:
name, weeks_worked, weekly_payment = match.groups()
else:
raise Exception('Could not match %s' % line)
# your code to update information
正则表达式看起来很复杂,其实很简单:
\(...\) matches the parentheses in the line
\s* matches optional spaces (it's not clear to me if you have spaces or not
in various places between words, so this matches just in case)
\d+ matches a number (1 or more digits)
[^']* matches anything except a quote (so matches the name)
(...) (without the \ backslashes) indicates a group that you want to read
afterwards by calling .groups()
这些是由http://docs.python.org/2/library/re.html中描述的更简单的部分(如*
和)构建+
的\d
如果您想对多行重复此操作,您可能需要以下内容:
name, weeks_worked, weekly_payment = [], [], []
for line in file.readlines():
match = line_format.match(line)
if match:
name.append(match.group(1))
weeks_worked.append(match.group(2))
weekly_payment.append(match.group(3))
else:
raise ...