简体   繁体   English

在python中读取逗号分隔的值,直到新的空白行字符

[英]Reading comma separated values in python until new blank line character

I want to read input from STDIN like this: 我想像这样从STDIN读取输入:

1,0
0,0
1,0
1,0 

and so on until the new line is empty(\\n). 依此类推,直到新行为空(\\ n)。 This signifies the end of the input. 这表示输入结束。

I did this 我做了这个

while (raw_input()!='\n'):
    actual,predicted=raw_input().split(',')

Gave me this error when I entered "enter" in last input 当我在最后一个输入中输入“输入”时给了我这个错误

0,0
0,1
1,0
1,1
1,1

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-23-3ec5186ad531> in <module>()
      5 
      6 while (raw_input()!='\n'):
----> 7     actual,predicted=raw_input().split(',')
      8     if (actual==1 and predicted==1):
      9         t_p+=50

ValueError: need more than 1 value to unpack

What's wrong? 怎么了?

OK, there are two problems here: raw_input strips the trailing newline, so a blank input becomes an empty string, not a newline. 好的,这里有两个问题: raw_input删除尾随的换行符,因此空白输入变为空字符串,而不是换行符。

The larger issue is that raw_input consumes the input, so your code won't work properly - it will only process every second line. 更大的问题是raw_input使用了输入,因此您的代码将无法正常工作-仅处理第二行。 The while loop calls raw_input (which uses up some input and discards it), then the body of the loop calls it again and assigns it to actual and predicted. while循环调用raw_input(使用完一些输入并将其丢弃),然后循环主体再次调用它,并将其分配给实际的和预测的。

The python idiom for this task is a while True: loop containing a break : 此任务的python习惯用法是while True:包含break循环:

while True:
    line = raw_input()
    if not line:
        break
    actual, predicted = line.split(",")
    print("a, p", actual, predicted)
print("done!")

raw_input() strips the trailing newline, so you want to compare to '' . raw_input()所以你要比较去除结尾的换行符, ''

But you're also reading two lines at a time in your loop, where I think you want something more like: 但是您还需要在循环中一次读取两行,我想您需要的是更多类似内容:

data = raw_input()
while (data != ''):
    actual,predicted=data.split(',')
    data = raw_input()

raw_input is really used when you're writing a user-interactive program. 编写用户交互程序时,实际上会使用raw_input It sounds like your program is a more typical UNIX program which processes file input. 听起来您的程序是处理文件输入的更典型的UNIX程序。

sys.stdin is an open file. sys.stdin是一个打开的文件。 Because of this, you can use my favorite feature of Python which is iterating over each line in a file. 因此,您可以使用我最喜欢的Python功能,它在文件的每一行上进行迭代。 Ditch the raw_input altogether and just treat your data as if it were a file: 完全raw_input ,只将数据视为文件即可:

for line in sys.stdin:
    line = line.strip()
    parts = line.split(',')

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

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