【问题标题】:SyntaxError: invalid syntax line 138 unexpected errorSyntaxError:无效的语法第 138 行意外错误
【发布时间】:2016-08-02 01:59:21
【问题描述】:

我正在尝试编写一个脚本来回答我正在做的课程中的一个问题。我不断收到 SyntaxError: invalid syntax line 138 这有点奇怪。这是我的脚本。如果有人能解释如何解决这个问题,那就太好了。谢谢

class Message(object):

    def __init__(self, text):

        self.message_text = text
        self.valid_words = load_words(WORDLIST_FILENAME)


    def get_message_text(self):

        return self.message_text


    def get_valid_words(self):

        return self.valid_words[:]

    def build_shift_dict(self, shift):

        lc_str = string.ascii_lowercase
        uc_str = string.ascii_uppercase

        shifted_dict = {}

    
        for ltr in lc_str:
            if lc_str.index(ltr) + shift < 26:
                shifted_dict[ltr] = lc_str[lc_str.index(ltr) + shift]
            else:
                shifted_dict[ltr] = lc_str[lc_str.index(ltr)-26+shift]

        for ltr in uc_str:
            if uc_str.index(ltr) + shift < 26:
                shifted_dict[ltr] = uc_str[uc_str.index(ltr) + shift]
            else:
                shifted_dict[ltr] = uc_str[uc_str.index(ltr)-26+shift]

        return shifted_dict


    def apply_shift(self, shift):

        cipher = self.build_shift_dict(shift)
        ciphertext = ""

        for char in self.message_text:
            if char in cipher:
                ciphertext = ciphertext + cipher[char]
            else:
                ciphertext = ciphertext + char

        return ciphertext

【问题讨论】:

  • 这里的行数远远少于 138 行。这些行之一是您的代码的第 138 行吗?如果是这样,你能告诉我们是哪一个吗?
  • 你能给出确切的信息吗?我们不知道第 138 行到底是什么。
  • edit您的帖子为我们提供minimal reproducible example

标签: python python-2.7 syntax-error


【解决方案1】:

这两行之间:

shifted_dict = {}

for ltr in lc_str:

您有一个非 ASCII 字符 ('\xe2')。删除它。

(如果您尝试在 Python 解释器中加载代码,Python 会准确地告诉您这一点。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-29
    • 2021-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-10
    • 1970-01-01
    • 2016-03-11
    相关资源
    最近更新 更多