gpt4 book ai didi

python - 为什么这在 Windows 上的 Python 3 IDLE 中有效,而在 Ubuntu 上的终端中无效?

转载 作者:行者123 更新时间:2023-11-30 23:47:23 35 4
gpt4 key购买 nike

我有一个程序,我使用 input()从 STDIN 获取输入。

我使用输入读取一行中的第一个单词并将其用作字典键,将每个后续单词添加到列表中,该列表是上述键的值。

输入位于文件 names.txt 中:

Victor Bertha Amy Diane Erika Clare
Wyatt Diane Bertha Amy Clare Erika
Xavier Bertha Erika Clare Diane Amy
Yancey Amy Diane Clare Bertha Erika
Zeus Bertha Diane Amy Erika Clare

Amy Zeus Victor Wyatt Yancey Xavier
Bertha Xavier Wyatt Yancey Victor Zeus
Clare Wyatt Xavier Yancey Zeus Victor
Diane Victor Zeus Yancey Xavier Wyatt
Erika Yancey Wyatt Zeus Xavier Victor

例如,men["Victor"] = ["Bertha","Amy","Diane","Erika","Clare"] .

代码位于文件 GS.py 中(Gale-Shapley 的实现):

if __name__ == "__main__":

## Data Dictionary

''' Name : Preferences '''
men = dict()
women = dict()

''' List of unmatched men '''
freeMen = list()

''' Name : How far down in preferences '''
count = dict()

''' Name : Current Match '''
wife = dict()
husband = dict()

## Reading Input
data = input("").split("\n")
print(data)
readingMen = True
for l in data:
line = l.split()
print(line)
if len(line) > 1:
newPerson = line[0]
newPersonPreferences = list()
for i in range(1,len(line)):
newPersonPreferences.append(line[i])
if readingMen:
print("man")
print(newPersonPreferences)
men[newPerson] = newPersonPreferences
wife[newPerson] = 0
count[newPerson] = 0
freeMen.append(newPerson)
else:
print("woman")
print(newPersonPreferences)
women[newPerson] = newPersonPreferences
husband[newPerson] = 0
elif len(line) == 1:
raise IOError(l + "\nis an invalid line.")
else:
readingMen = False

## Proposing
while len(freeMen) != 0:
m = freeMen[0]
w = men[m][count[m]]
count[m] += 1
if husband[w] == 0:
husband[w] = m
wife[m] = w
freeMen.remove(m)
else:
try:
if women[w].index(husband[w], women[w].index(m)):
freeMen.append(husband[w])
wife[husband[w]] = 0
husband[w] = m
wife[m] = w
freeMen.remove(m)
except ValueError:
pass

## Match Printing
print()
for m in wife:
print(m, wife[m])

在 Windows 上使用 IDLE 时,我只需粘贴此文件的内容并按 Enter 键即可运行。

但是使用 Ubuntu,我会 python3 GS.py < names.txt我得到这个:

me@glados:~$ python3 GS.py < names.txt
['Victor Bertha Amy Diane Erika Clare']
['Victor', 'Bertha', 'Amy', 'Diane', 'Erika', 'Clare']
man
['Bertha', 'Amy', 'Diane', 'Erika', 'Clare']
Traceback (most recent call last):
File "GS.py", line 83, in <module>
if husband[w] == 0:
KeyError: 'Bertha'

(已编辑)现在当我这样做时cat names.txt | python3 GS.py我明白了:

ajg9132@glados:~$ cat names.txt | python GS.py
Traceback (most recent call last):
File "GS.py", line 50, in <module>
data = input("").split("\n")
File "<string>", line 1
Victor Bertha Amy Diane Erika Clare
^
SyntaxError: invalid syntax

我不知道该怎么办 - 对 I/O 有点无知。有什么帮助吗?

编辑说明:我认为我给出的两个不同的 bash 命令是等效的,但话又说回来,我是个菜鸟,所以解释它们为什么不同也会有所帮助。 .

为了消除歧义,这是一份 Algo 作业......(遗憾的是我了解算法,但不了解操作系统的低级细节)并且我需要有一个特定的输入和输出方案。例如

spock $ java GS
Victor Bertha Amy Diane Erika Clare
Wyatt Diane Bertha Amy Clare Erika
Xavier Bertha Erika Clare Diane Amy
Yancey Amy Diane Clare Bertha Erika
Zeus Bertha Diane Amy Erika Clare

Amy Zeus Victor Wyatt Yancey Xavier
Bertha Xavier Wyatt Yancey Victor Zeus
Clare Wyatt Xavier Yancey Zeus Victor
Diane Victor Zeus Yancey Xavier Wyatt
Erika Yancey Wyatt Zeus Xavier Victor

Victor Amy
Wyatt Clare
Xavier Bertha
Yancy Erika
Zeus Diane
spock $

我没有这样做的唯一原因是,将几行文本粘贴到 PuTTY 中会使 bash 尝试将每一行解释为命令。我什至不能。

最佳答案

input()的含义已改变。

在 Python 3.2 中:http://docs.python.org/py3k/library/functions.html#input

在 Python 2.7.2 中:http://docs.python.org/library/functions.html#input

通过两个小型测试程序,您可以更轻松地看到这一点。唯一的区别是一个使用 Python 2.7 解释器,另一个使用 Python 3.2 解释器:

$ cat input27.py 
#!/usr/bin/python2.7
data = input("")

for l in data.split("\n"):
print(l)
$ cat input32.py
#!/usr/bin/python3.2
data = input("")

for l in data.split("\n"):
print(l)
$ ./input27.py < names.txt
Traceback (most recent call last):
File "./input27.py", line 2, in <module>
data = input("")
File "<string>", line 1
Victor Bertha Amy Diane Erika Clare
^
SyntaxError: invalid syntax
$ ./input32.py < names.txt
Victor Bertha Amy Diane Erika Clare
$

请注意,即使 Python 3.2 版本不会抛出错误,它也不会打印 names.txt 中的所有行。正如人们所预料的那样。

我不认为input()方法值得使用。更容易使用新奇的 for line in file: 相反的方法:

$ cat fixed_input27.py 
#!/usr/bin/python2.7

import sys

for line in sys.stdin:
print(line.split()[0])
$ cat fixed_input32.py
#!/usr/bin/python3.2

import sys

for line in sys.stdin:
print(line.split()[0])
$ ./fixed_input27.py < names.txt
Victor
Wyatt
Xavier
Yancey
Zeus
Amy
Bertha
Clare
Diane
Erika
$ ./fixed_input32.py < names.txt
Victor
Wyatt
Xavier
Yancey
Zeus
Amy
Bertha
Clare
Diane
Erika
$

(我从 names.txt 中删除了一个空行,因为它导致这个简单的程序抛出错误。这实际上不会成为您成熟的程序中的问题,因为您正确地处理了空行。)

我无法解释为什么input() 确实在Windows下工作,但是input()感觉这是一个足够可怕的界面(谁认为通过 eval 运行用户提供的输入是一个好主意?!?天哪)只需重写它。

更新

好吧,我很感兴趣,一直想解决这个问题。我把你所有的调试代码都拿出来并改用 for l in sys.stdin:方法:

$ ./GS.py 
Victor Bertha Amy Diane Erika Clare
Wyatt Diane Bertha Amy Clare Erika
Xavier Bertha Erika Clare Diane Amy
Yancey Amy Diane Clare Bertha Erika
Zeus Bertha Diane Amy Erika Clare

Amy Zeus Victor Wyatt Yancey Xavier
Bertha Xavier Wyatt Yancey Victor Zeus
Clare Wyatt Xavier Yancey Zeus Victor
Diane Victor Zeus Yancey Xavier Wyatt
Erika Yancey Wyatt Zeus Xavier Victor

Wyatt Clare
Xavier Bertha
Yancey Erika
Zeus Diane
Victor Amy
$ cat GS.py
#!/usr/bin/python3.2

if __name__ == "__main__":
import sys

## Data Dictionary

''' Name : Preferences '''
men = dict()
women = dict()

''' List of unmatched men '''
freeMen = list()

''' Name : How far down in preferences '''
count = dict()

''' Name : Current Match '''
wife = dict()
husband = dict()

## Reading Input
readingMen = True
for l in sys.stdin:
line = l.split()
if len(line) > 1:
newPerson = line[0]
newPersonPreferences = list()
for i in range(1,len(line)):
newPersonPreferences.append(line[i])
if readingMen:
men[newPerson] = newPersonPreferences
wife[newPerson] = 0
count[newPerson] = 0
freeMen.append(newPerson)
else:
women[newPerson] = newPersonPreferences
husband[newPerson] = 0
elif len(line) == 1:
raise IOError(l + "\nis an invalid line.")
else:
readingMen = False

## Proposing
while len(freeMen) != 0:
m = freeMen[0]
w = men[m][count[m]]
count[m] += 1
if husband[w] == 0:
husband[w] = m
wife[m] = w
freeMen.remove(m)
else:
try:
if women[w].index(husband[w], women[w].index(m)):
freeMen.append(husband[w])
wife[husband[w]] = 0
husband[w] = m
wife[m] = w
freeMen.remove(m)
except ValueError:
pass

## Match Printing
print()
for m in wife:
print(m, wife[m])

$

请注意,您必须点击 ^D当您完成粘贴输入时,如果您以这种方式运行它。 (我非常更喜欢 IO 重定向 ./GS.py < names.txt ,但如果你的教授会复制和粘贴,那么请确保你的教授知道点击 ^D 来表示输入结束。)

关于python - 为什么这在 Windows 上的 Python 3 IDLE 中有效,而在 Ubuntu 上的终端中无效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8413200/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com