如何从python中的stdin逐行读取 [英] How to read line by line from stdin in python
问题描述
每个人都知道如何在 C 中计算 STDIN 中的字符数.但是,当我尝试在 python3 中执行此操作时,我发现这是一个难题.(counter.py)
Everyone knows how to count the characters from STDIN in C. However, when I tried to do that in python3, I find it is a puzzle. (counter.py)
import sys
chrCounter = 0
for line in sys.stdin.readline():
chrCounter += len(line)
print(chrCounter)
然后我尝试通过
python3 counter.py < counter.py
答案只是第一行import sys"的长度.事实上,程序只从标准输入中读取第一行,并丢弃其余的行.
The answer is only the length of the first line "import sys". In fact, the program ONLY read the first line from the standard input, and discard the rest of them.
如果我用 sys.stdin.read() 代替 sys.stdin.readline 就可以了
It will be work if I take the place of sys.stdin.readline by sys.stdin.read()
import sys
print(len(sys.stdin.read()))
但是,很明显,该程序不适合大量输入.请给我一个优雅的解决方案.谢谢!
However, it is obviously, that the program is NOT suitable for a large input. Please give me a elegant solution. Thank you!
推荐答案
更简单:
for line in sys.stdin:
chrCounter += len(line)
类文件对象sys.stdin
会自动逐行迭代;如果你调用 .readline()
,你只会读取第一行(并逐个字符地迭代);如果您调用 read()
,那么您会将整个输入读入一个字符串,然后逐个字符地遍历那个.
The file-like object sys.stdin
is automatically iterated over line by line; if you call .readline()
on it, you only read the first line (and iterate over that character-by-character); if you call read()
, then you'll read the entire input into a single string and iterate over that character-by.character.
这篇关于如何从python中的stdin逐行读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!