2013-08-06 120 views
0

Python 3程序允许用户从员工姓名列表中进行选择。 数据上的文本文件看起来像这样认为:(“拉里”,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)) 

回答

0

当前正在分配的前三行形成文件nameweeks_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() 

和这些都是从简单的部分建(如*+\d),其描述在http://docs.python.org/2/library/re.html

如果你想重复是很多行,你可能想要类似的东西:

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 ... 
+0

是否没有一种方法有一个for循环,查看文本文件中的每个元素并为其指定一个索引号。那么我的变量可以匹配索引号? –

+0

请参阅额外编辑。 –

相关问题