【问题标题】:Read from text file and assign data to new variable从文本文件中读取并将数据分配给新变量
【发布时间】:2013-08-07 08:06:09
【问题描述】:

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))

【问题讨论】:

    标签: file variables python-3.x


    【解决方案1】:

    目前您将文件的前三行分配给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()
    

    这些是由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 ...
    

    【讨论】:

    • 有没有办法让 for 循环查看文本文件中的每个元素并为其分配索引号。那么我的变量可以匹配索引号吗?
    猜你喜欢
    • 1970-01-01
    • 2013-07-15
    • 2013-12-09
    • 1970-01-01
    • 2019-05-24
    • 2023-03-30
    • 2019-12-22
    • 2018-08-22
    • 2015-12-12
    相关资源
    最近更新 更多