简体   繁体   English

拆分Python函数无法正常工作

[英]Split Python Function is not working as expected

If I have a file (users.txt) with the following information formatted: 如果我有一个格式为以下信息的文件(users.txt):

x y z(t)

x y z(t)

How can I write a python function that reads in the file (users.txt) and uses the split function to break up each line of the file into three variables: 如何编写一个读取文件(users.txt)并使用split函数将文件的每一行分成三个变量的python函数:

who for x who x
where for y y where
when_and_time for z(t) z(t) when_and_time

and print s to the screen such that the format is who on where at when_and_time or with the variables x on y at z(t) 然后将s print到屏幕上,以便格式为who on where at when_and_timex on y at z(t)的变量x on y at z(t)

What I have so far is: 到目前为止,我有:

user_info = open("~/users.txt").read()
for line in user_info:
    positions = line.split(',')
    who = positions[0]
    where = positions[1]
    when_and_time = positions[2]
    print(who + " on " + where + " at " + when_and_time)   # I press enter at this point

It gives me the prompt for more commands, at which point I press enter again and receive the following: 它提示我输入更多命令,这时我再次按Enter键并收到以下信息:

Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
IndexError: list index out of range

What am I doing wrong?? 我究竟做错了什么??

The issue here is that you're doing split(",") , which will split the string on comma characters. 这里的问题是您正在执行split(",") ,它将字符串分割成逗号。 Since you appear to have formatted your string with spaces, it's not splitting it anywhere, so you only get one element in your list. 由于您似乎用空格格式化了字符串,因此不会将其拆分到任何地方,因此列表中只包含一个元素。 You probably want to use split() with no argument to split on any whitespace. 您可能想使用不带参数的split()在任何空白处进行拆分。

if you read file line by line will be better then you can split on spaces: 如果逐行阅读文件会更好,那么可以在空格处分割:

f=open('your_file')
for x in f:
    x=x.split()  # now here x contain all variables that are separated by space
    # do your stuff with x

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM