Skip to main content
 首页 » 编程设计

Python 值错误 : chr() arg not in range(256)

2025年05月04日29zhoujg

所以我正在学习python并重做一些旧项目。该项目涉及从命令行接收字典和要翻译的消息,然后翻译消息。 (例如:“btw, hello how r u”将被翻译成“顺便说一下,你好吗”。

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

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 代码点可以达到更高的值。