Python ValueError:chr()arg不在范围内(256)

时间:2014-12-06 03:12:11

标签: python dictionary translate

所以我正在学习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会抛出这个错误...它可能是我错过的蠢事

2 个答案:

答案 0 :(得分:5)

问题在于,您使用chr转换的字符不在接受的范围内(range(256))。十进制中的值0x2018为8216.

结帐unichr,另见chr

答案 1 :(得分:4)

如果您使用Python 3,

chr(0x2018)将起作用。

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