如何在Python空间拆分列表

2024-10-04 03:24:36 发布

您现在位置:Python中文网/ 问答频道 /正文

Python初学者。 我有一个函数,它应该打开两个文件,在空格处拆分它们,并将它们存储在列表中,以便在另一个函数中访问。 我的第一个功能是:

listinput1 = input("Enter the name of the first file that you want to open: ")
listinput2 = input("Enter the name of the first file that you want to open: ")
list1 = open(listinput1)
list1 = list(list1)
list2 = open(listinput2)
list2 = list(list2)
metrics = plag(list1, list2)
print(metrics)

但是当我执行第二个函数时,我看到列表并没有像我预期的那样在空格处拆分。我尝试了split函数,还尝试了使用for循环来迭代列表的每个增量。你知道吗


Tags: ofthe函数name列表inputthatopen
1条回答
网友
1楼 · 发布于 2024-10-04 03:24:36

一些建议:

  • 当你open()一个文件时,你也需要close()它。您没有这样做(一般来说,单独做是个坏主意,因为如果程序首先遇到异常,可能会错过结束)。你知道吗

    这里首选的Python习惯用法是with open(path) as f

    with open(listinput1) as f:
       # do stuff with f
    

  • 调用open(listinput1)时,会得到一个file对象。对此调用list()将获得文件中的行列表,例如:

    # colours.txt
    amber
    blue
    crimson | dark green
    

    with open('colours.txt') as f:
        print(list(f))  # ['amber', 'blue', 'crimson | dark green']
    

    要从文件中获取包含文本的字符串,请对对象调用read()方法,然后对该字符串使用split()方法。你知道吗

    with open('colours.txt') as f:
        text = f.read()         #  'amber\nblue\ncrimson | dark green'
        print(text.split(' '))  # ['amber\nblue\ncrimson', '|', 'dark', 'green']
    

  • 你要了两次第一份文件。第二个字符串是否应该是“输入要打开的第二个文件的名称”?

以下是代码的更新版本,其中包含这些更改:

path1 = input("Enter the name of the first file that you want to open: ")
path2 = input("Enter the name of the second file that you want to open: ")

with open(path1) as f1:
    list1 = f1.read().split(' ')

with open(path2) as f2:
    list2 = f2.read().split(' ')

相关问题 更多 >