Python如何读取用户的输入直到EOF?

11

我在UVa OJ上遇到了这个问题。272-Text Quotes

总的来说,这个问题非常简单。但问题在于我无法读取输入。输入以文本行的形式提供,输入结束标志为EOF。 在C/C ++中,可以通过while循环来完成:

while( scanf("%s",&s)!=EOF ) { //do something } 

如何在Python中实现这一点?

我已经在网上搜索了,但没有找到令人满意的答案。

请注意,输入必须从控制台读取,而不是从文件中读取。


1
可能是如何读取用户输入直到EOF?的重复问题。 - MrSeeker
5个回答

8
您可以使用 sys 模块:
import sys

complete_input = sys.stdin.read()

sys.stdin 是一个类似文件的对象,您可以像处理Python 文件对象一样对待它。

根据文档:

Help on built-in function read:

read(size=-1, /) method of _io.TextIOWrapper instance Read at most n characters from stream.

Read from underlying buffer until we have n characters or we hit EOF.
If n is negative or omitted, read until EOF.

这种情况下,输入何时终止?您能否查看问题中提供的输入格式[链接在问题中提供]。我不确定这是否适用于此。谢谢。 - rohan
@rohan EOF字符与C/C++相同。 - user1785721

6
你可以使用Python中的sysos模块从控制台读取输入直到文件结尾。我已经在像SPOJ这样的在线评测系统中多次使用这些方法。 第一种方法(推荐):
from sys import stdin

for line in stdin:
    if line == '': # If empty string is read then stop the loop
        break
    process(line) # perform some operation(s) on given string

请注意,您读取的每一行末尾都会有一个换行符\n。如果您想避免在打印line时打印2个换行符,请使用print(line, end='')
第二种方法:
import os
# here 0 and 10**6 represents starting point and end point in bytes.
lines = os.read(0, 10**6).strip().splitlines() 
for x in lines:
    line = x.decode('utf-8') # convert bytes-like object to string
    print(line)

这种方法并不适用于所有的在线评测网站,但它是从文件或控制台读取输入的最快的方式。
第三种方法:
while True:
    line = input()
    if line == '':
        break
    process(line)

如果您仍在使用Python 2,请将input()替换为raw_input()


通过比较方法1和方法2读取输入所需的时间,可以清楚地了解它们之间的差异。 - rohan

5

针对HackerRank和HackerEarth平台,以下实现方式是首选:

while True:
try :
    line = input()
    ...
except EOFError:
    break;

3
这是您可以执行的方法:
while True:
   try :
      line = input()
      ...
   except EOFError:
      pass

1

1
谢谢这个想法。这当然可以做到,但这将导致问题解决方案包括一个完整的模块来读取输入。考虑到这是一个受限制的问题,效率并不高。 - rohan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接