簡體   English   中英

Python 當我將多行文本粘貼到輸入提示時腳本死掉

[英]Python script dies when I paste multiline text into input prompt

我做了一個程序:

import collections
x = input("Enter in text: ")
x_counter = collections.Counter()
x_counter.update(x)
print("Your sequence contains:\n")
for i in '`1234567890-=qwertyuiop[]\asdfghjkl;zxcvbnm,./~!@#$%^&*()_+QWERTYUIOP\
{}|ASDFGHJKL:"ZXCVBNM<>?':
    print(i, x_counter[i])

這會打印出一個字母在文本中被使用的次數。 當用戶輸入較小的文本時,例如一段文字……程序運行良好。 當用戶輸入很長的文本時,比如 5 段……程序退出並以 bash 命令運行所有輸入……這是為什么???

這是因為input僅從用戶那里獲取一行,如以下示例所示:

pax> cat qq.py
x = raw_input ("blah: ") # using raw_input for Python 2
print x

pax> python qq.py
blah: hello<ENTER>
hello

pax> there<ENTER>
bash: there: command not found

pax> 

一種可能性是從文件中讀取信息而不是使用input ,但您也可以執行以下操作:

def getline():
    try:
        x = raw_input ("Enter text (or eof): ")
    except EOFError:
        return ""
    return x + "\n"

text = ""
line = getline()
while line != "":
    text = text + line;
    line = getline()
print "\n===\n" + text

它將繼續讀取用戶的輸入,直到他們以 EOF(Linux 下的 CTRL-D)結束輸入:

pax> python qq.py
Enter text (or eof): Hello there,
Enter text (or eof): 
Enter text (or eof): my name is Pax.
Enter text (or eof): <CTRL-D>
===
Hello there,

my name is Pax.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM