所以我正在学习python并重做一些旧项目。该项目涉及从字典中获取字典和要翻译的消息,并翻译该消息。 (例如:“顺便说一句,你好,你好吗?”将被翻译成“顺便问一下,你好吗”。

我们正在使用教授提供的扫描仪来读取令牌和字符串。如有必要,我也可以在此处发布。这是我的错误:

Nathans-Air-4:py1 Nathan$ python translate.py test.xlt test.msg
Traceback (most recent call last):
  File "translate.py", line 26, in <module>
    main()
  File "translate.py", line 13, in main
    dictionary,count = makeDictionary(commandDict)
  File "/Users/Nathan/cs150/extra/py1/support.py", line 12, in makeDictionary
    string = s.readstring()
  File "/Users/Nathan/cs150/extra/py1/scanner.py", line 105, in readstring
    return self._getString()
  File "/Users/Nathan/cs150/extra/py1/scanner.py", line 251, in _getString
    if (delimiter == chr(0x2018)):
ValueError: chr() arg not in range(256)


这是我的主要translate.py文件:

from support import *
from scanner import *
import sys

def main():
    arguments = len(sys.argv)
    if arguments != 3:
        print'Need two arguments!\n'
        exit(1)
    commandDict = sys.argv[1]
    commandMessage = sys.argv[2]

    dictionary,count = makeDictionary(commandDict)

    message,messageCount = makeMessage(commandMessage)

    print(dictionary)
    print(message)

    i = 0
    while count < messageCount:
        translation = translate(message[i],dictionary,messageCount)
        print(translation)
        count = count + 1
        i = i +1
    main()


这是我正在使用的support.py文件...

from scanner import *

def makeDictionary(filename):
    fp = open(filename,"r")

    s = Scanner(filename)
    lyst = []
    token = s.readtoken()
    count = 0
    while (token != ""):
        lyst.append(token)
        string = s.readstring()
        count = count+1
        lyst.append(string)
        token = s.readtoken()
    return lyst,count

def translate(word,dictionary,count):
    i = 0
    while i != count:
        if word == dictionary[i]:
            return dictionary[i+1]
            i = i+1
        else:
            return word
            i = i+1
    return 0

def makeMessage(filename):
    fp = open(filename,"r")

    s = Scanner(filename)
    lyst2 = []
    string = s.readtoken()
    count = 0
    while (string != ""):
        lyst2.append(string)
        string = s.readtoken()
        count = count +  1
    return lyst2,count


有人知道这是怎么回事吗?我已经浏览了好几次,但我不知道为什么readString会引发此错误...我可能错过了一些愚蠢的事情

最佳答案

如果您使用Python 3,chr(0x2018)将起作用。

您有为Python 3编写的代码,但可以在Python 2中运行。在Python 2中,chr将为您提供ASCII范围内的一个字符串。这是一个8位字符串,因此chr的最大参数值为255。在Python 3中,您将获得一个unicode字符,并且unicode代码点可以达到更高的值。

关于python - Python ValueError:chr()arg不在范围内(256),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27327901/

10-13 06:43
查看更多