Python: 吸收键盘输入中的换行符

3 投票
2 回答
1271 浏览
提问于 2025-04-18 13:52

我有一个关于从键盘输入多行内容的问题。看起来我的程序没有正确处理换行符。结果是,当输入处理完后,程序似乎认为还有一些换行符没有被处理,这个数量和输入中的换行符数量是一样的。

我查看了sys模块(sys.stdin.flush())、msvsrc模块(msvcrt.kbhit()和msvcrt.getch())、raw_input,并尝试了我能想到的所有方法,但都没有找到解决办法。也许strip()可以解决这个问题,但我还没搞明白怎么在一般情况下使用它。

我得到的输出是这样的:

Enter a string: def countLetters():
    s = input("Enter a string: ")
    d = histogram(s.upper())
    printSortedDict(d, True)
('T', 3)
('E', 3)
('F', 1)
('D', 1)
(' ', 1)
(':', 1)
('R', 1)
('(', 1)
('N', 1)
(')', 1)
('L', 1)
('U', 1)
('C', 1)
('O', 1)
('S', 1)

Continue (yes/no): 
Continue (yes/no): 
Continue (yes/no): 
Continue (yes/no): 

我希望输出中只显示一次“继续(是/否):”。看起来input()函数处理了最后一个换行符(这很正常),但没有处理中间的换行符。这些换行符似乎被当作“继续(是/否)”语句的输入。

我使用的是Python 3.4.1。我在Win8上开发,但希望这个解决方案也能在Linux上运行(以防解决方案是特定于某个平台的)。这是程序。最简单的方法是直接复制源代码,然后将其作为输入粘贴到程序中。

#
# letterCountDict - count letters of input.  uses a dict()
#
"""letterCountDict - enter a string and the count of each character is returned """

# stolen from p. 122 of "Python for Software Design" by Allen B. Downey
def histogram(s):
    """builds a histogram from the characters of string s"""
    d = dict()
    for c in s:
        if c in d:
            d[c] += 1
        else:
            d[c] = 1
    return d

def printSortedDict(d, r=False):
    """sort and print a doctionary.  r == True indicates reserve sort."""
    sl = sorted(d.items(), key=lambda x: x[1], reverse=r)
    for i in range(len(sl)):
        print(sl[i])

def countLetters():
    s = input("Enter a string: ")
    d = histogram(s.upper())
    printSortedDict(d, True)

answerList = ["yes", "no"]
done = False
while not done:
    countLetters()
    ans = ""
    while ans not in answerList:
        ans = input("\nContinue (yes/no): ").replace(" ", "").lower()
    if ans == "no":
        done = True

2 个回答

-1

当你从这一行获取输入时

s = input("Enter a string: ") 可以换成

s = input("Enter a string: ").replace('\n', '')

这里的意思是,原本你输入的内容可能会包含换行符(也就是按下回车键时产生的),所以我们用 .replace('\n', '') 这个方法把换行符去掉。这样,你得到的字符串就不会有多余的换行了。

3

input() 这个函数一次只能读取一行内容。每次调用 input() 都只能获取到一行。

比如,你第一次调用 input 的时候:

    s = input("Enter a string: ")

它会接收到这一行:

def countLetters():

没错,你可以看到这行里有三个 T、三个 E,等等。

接下来你又调用 input(),这次是:

    ans = input("\nContinue (yes/no): ").replace(" ", "").lower()

你输入的是:

s = input("Enter a string: ")

因为你的回答既不是 'yes' 也不是 'no',所以循环会继续问你。这次你输入:

d = histogram(s.upper())

这同样也不是 'yes' 也不是 'no'

这个过程会一直持续,直到你厌倦了不停地输入无意义的回答。最后,你输入了 "no",游戏才结束。

如果你想一次读取多行内容,可以试试 sys.stdin.read() 或者 sys.stdin.readlines()。比如:

import sys
def countLetters():
    print("Enter several lines, followed by the EOF signal (^D or ^Z)")
    s = sys.stdin.read()
    d = histogram(s.upper())
    printSortedDict(d, True)

撰写回答