【问题标题】:How to run something on each line of txt file?如何在 txt 文件的每一行上运行一些东西?
【发布时间】:2017-11-26 19:13:37
【问题描述】:

我试图让它在 .txt 文件的每一行上运行。

D1 =int(lines[0])*10
D2 =int(lines[1])*9
D3 =int(lines[2])*8
D4 =int(lines[3])*7
D5 =int(lines[4])*6
D6 =int(lines[5])*5
D7 =int(lines[6])*4
D8 =int(lines[7])*3
D9 =int(lines[8])*2
D10=int(line[9])*1
Sum =(D1+D2+D3+D4+D5+D6+D7+D8+D9)
Mod = Sum % 11

D11= 11 - Mod
if D11 == 10:
    D11 = 'X'

基本上,文本文件包含 ISBN-10 数字,我需要通过对文本文件中的每个数字运行此代码来验证这些数字。这是定义行的地方,因为文本文件包含“-”,我需要在开始上面显示的过程之前删除那些。

filename = input("Enter the name of the .txt file: ")
file = open(filename, "r")
lines = file.read()
if "-" in lines:
    lines = lines.replace("-", "")
lines = file.readline()
while lines:
    D1 =int(lines[0])*10
    D2 =int(lines[1])*9
    D3 =int(lines[2])*8
    D4 =int(lines[3])*7
    D5 =int(lines[4])*6
    D6 =int(lines[5])*5
    D7 =int(lines[6])*4
    D8 =int(lines[7])*3
    D9 =int(lines[8])*2
    D10=int(lines[9])*1
    Sum =(D1+D2+D3+D4+D5+D6+D7+D8+D9)
    Mod = Sum % 11

    D11= 11 - Mod
    if D11 == 10:
        D11 = 'X'
    if D10 == D11:
        print("Your ISBN-10's are Valid!")
    else:
        print("Your ISBN-10's are invalid")

【问题讨论】:

  • 那么每一行都有自己的ISBN-10 号码吗?或者每一行是数字中的一个数字 - 总共11行。
  • @JoeIddon 每行都有一个完整的 ISBN-10 编号
  • lines 变量中的内容。它在哪里定义?这可能与给你一个好的答案有关。
  • @martineau 我更新了帖子以包含更多代码

标签: python


【解决方案1】:

您可以使用for 循环:

for i,line in enumerate(textFile):
    #code to run on each line  

其中 line 是 loop 中当前行的值,i 是行号,所以假设您的文本文件是:

John
Doe

那么for 循环将是:

i as 0
line as John

在第一次运行时等等。

【讨论】:

  • enumerate 创建一个元组,因此整段代码 enumerate(list_item) 将等于(位置,值)
【解决方案2】:

您不必使用while 来迭代文件的每一行和每行中的每个数字。
你必须使用 for 循环和 enumerate() 这样的内置函数:

filename = input("Enter the name of the .txt file: ")
file = open(filename)
lines = file.readlines()

# # for testing
# lines = [
# '1-2345678-90\n',  # invalid
# '18-619727-17\n'  # valid
# ]

# iterate on lines
for line in lines:
    SUM = 0

    # remove '\n', new line, from line
    line = line.strip()

    # remove '-' from line
    line = ''.join(digit for digit in line if digit != '-')

    # iterate on line's digits
    for i, digit in enumerate(line):
        SUM += int(digit) * (len(line) - i)

    Mod = SUM % 11

    # print line for demonstration
    print('ISBN-10: ', line)

    # zero remainder = valid ISBN
    if Mod == 0:  # if not Mod:
        print("Your ISBN-10's are Valid!")
    else:
        print("Your ISBN-10's are invalid")

将打印:

ISBN-10:  1234567890
Your ISBN-10's are invalid
ISBN-10:  1861972717
Your ISBN-10's are Valid!

【讨论】:

    【解决方案3】:

    您可以在读取文件时即时进行处理。为了进行测试,我使用了一个名为 isbn10.txt 的文件,其中包含这些虚构的数字(在第一个有效的数字之后,后面的每个数字都是无效的)。

    0-201-53082-1
    0-20A-53082-1
    0-306-40615-2
    0-307-40615-9
    0-507-40615-X
    

    这是执行此操作的代码。 ISBN 的数字以 11 为基数,可以是 0-9 或 X,而不仅仅是 0-9,就像以 10 为基数一样,因此在进行计算时必须注意这一点。另请注意,以下内容不会将数字保存在任何地方,因此需要将其添加到您出于某种原因想要保留它们的位置。它还根据维基百科文章the subject 中的信息进行与验证它们的代码不同的计算(参见标题为ISBN-10 check digits 的部分)。在Check digits 上的维基百科文章的ISBN 10 部分中也有关于如何使用它的描述。

    # Dictionary to map ['0'-'9', 'X', 'x'] to [0-9, 10, 10].
    BASE10 = {digit: i for i, digit in enumerate('0123456789X')}
    BASE10['x'] = BASE10['X']  # Allow upper and lowercase 'x's.
    
    #filename = input("Enter the name of the .txt file: ")
    filename = 'isbn10.txt'  # Hardcoded for testing.
    
    invalid_numbers_count = 0
    with open(filename, "r") as file:
        for numbers_count, line in enumerate(file, 1):
            # Remove any leading or trailing whitespace and dashes from number.
            digits = line.rstrip().replace('-', '')
    
            try:
                chksum = sum((i * BASE10[digit]) for i, digit in enumerate(digits, 1))
            except KeyError:  # Invalid digit.
                chksum = 1  # Any non-multiple of 11.
    
            if chksum % 11 == 0:
                print('ISBN {} is valid'.format(line.strip()))
            else:
                print('ISBN {} is invalid'.format(line.strip()))
                invalid_numbers_count += 1
    
    print("{} of the {} ISBN-10's are invalid".format(
            invalid_numbers_count if invalid_numbers_count else "None",
            numbers_count))
    

    输出:

    ISBN 0-201-53082-1 is valid
    ISBN 0-20A-53082-1 is invalid
    ISBN 0-306-40615-2 is valid
    ISBN 0-307-40615-9 is invalid
    ISBN 0-507-40615-X is valid
    2 of the 5 ISBN-10's are invalid
    

    【讨论】:

      【解决方案4】:

      假设:

      with open("isbn_numbers.txt", "r") as fs:
          lines = fs.readlines() # will give a list 
      

      您可以遍历 lines 来计算总和,或者使用 _sum = sum(map(int, lines)) 假设您的 txt 文件中有数字。

      这里不要使用变量,而是使用已有的列表,然后使用索引获取值。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多