0

Python 3 程序允许人们从员工姓名列表中进行选择。保存在文本文件中的数据如下所示: ('larry', 3, 100) (作为人名、工作周数和付款)

我需要一种方法将文本文件的每个部分分配给一个新变量,以便用户可以输入新的周数,程序计算新的付款。

下面是我的代码,并试图弄清楚它。

import os
choices = [f for f in os.listdir(os.curdir) if f.endswith(".txt")]
print (choices)
emp_choice = input("choose an employee:")

file = open(emp_choice + ".txt")

data = file.readlines()
name = data[0]
weeks_worked = data[1]
weekly_payment= data[2]

new_weeks = int(input ("Enter new number of weeks"))
new_payment = new_weeks * weekly_payment
print (name + "will now be paid" + str(new_payment))
4

1 回答 1

0

目前您正在将文件的前三行分配给name,weeks_workedweekly_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 ...
于 2013-08-06T12:30:42.757 回答