[英]How to split lists at spaces 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循环对列表的每个增量进行迭代。
一些建议:
当您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(' ')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.