我最近下载了一个python程序,看看它是如何工作的。这是一个简单的文本程序演变,您输入一些文本,然后输出随机文本/数字/符号,直到演变为您输入的文本。该程序已经创建工作,这是问题,它没有,我不确定为什么。这是程序:
#-----------------------------------------------------
# Python 'Evolution of Text' Program
# More programs at: usingpython.com/programs
#-----------------------------------------------------
import string
import random
import time
possibleCharacters = string.ascii_lowercase + string.digits + string.ascii_uppercase + ' .,!?;:'
target = input("Enter your target text: ")
attemptThis = ''.join(random.choice(possibleCharacters) for i in range(len(target)))
attemptNext = ''
completed = False
generation = 0
while completed == False:
print(attemptThis)
attemptNext = ''
completed = True
for i in range(len(target)):
if attemptThis[i] != target[i]:
completed = False
attemptNext += random.choice(possibleCharacters)
else:
attemptNext += target[i]
generation += 1
attemptThis = attemptNext
time.sleep(0.1)
print("Target matched! That took " + str(generation) + " generation(s)")
所以,我在Python Canopy中运行了几次这些程序,这些是它给我的错误:
Welcome to Canopy's interactive data-analysis environment!
with pylab-backend set to: qt
Type '?' for more information.
In [1]: %run "c:\users\phillip\appdata\local\temp\tmpxe9get.py"
Enter your target text: Hellow World!
File "<string>", line 1
Hellow World!
^
SyntaxError: invalid syntax
In [2]: %run "c:\users\phillip\appdata\local\temp\tmpvj64ac.py"
Enter your target text: HellowWorld
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
c:\users\phillip\appdata\local\temp\tmpvj64ac.py in <module>()
10 possibleCharacters = string.ascii_lowercase + string.digits + string.ascii_uppercase + ' .,!?;:'
11
---> 12 target = input("Enter your target text: ")
13 attemptThis = ''.join(random.choice(possibleCharacters) for i in range(len(target)))
14 attemptNext = ''
C:\Users\Phillip\AppData\Local\Enthought\Canopy\App\appdata\canopy- 1.5.1.2730.win-x86_64\lib\site-packages\IPython\kernel\zmq\ipkernel.pyc in <lambda>(prompt)
362 if content.get('allow_stdin', False):
363 raw_input = lambda prompt='': self._raw_input(prompt, ident, parent)
--> 364 input = lambda prompt='': eval(raw_input(prompt))
365 else:
366 raw_input = input = lambda prompt='' : self._no_raw_input()
C:\Users\Phillip\AppData\Local\Enthought\Canopy\App\appdata\canopy 1.5.1.2730.win-x86_64\lib\site-packages\IPython\kernel\zmq\ipkernel.pyc in <module>()
NameError: name 'HellowWorld' is not defined
In [3]: %run "c:\users\phillip\appdata\local\temp\tmpulqoxo.py"
Enter your target text: What is wrong with this stupid program?
File "<string>", line 1
What is wrong with this stupid program?
^
SyntaxError: invalid syntax
我不确定我是否只是错误地输入我的文本,或者这是程序本身的问题。当单词间隔时,它会以随机字母(似乎小写)抛出无效语法。输入没有间距的单个字母或单词或单词组时,会抛出名称错误,就好像它正在尝试定义输入的文本一样。我真的不明白这些错误,所以任何帮助都会受到赞赏。
答案 0 :(得分:0)
是raw_input而不是input