如何在空格Python

时间:2015-11-14 17:00:02

标签: python list split

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循环迭代列表的每个增量。

1 个答案:

答案 0 :(得分:0)

一些建议:

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

    这里首选的Python习语是with open(path) as f

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

  • 当您致电open(listinput1)时,您会收到一个文件对象。在此上调用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(' ')