【问题标题】:IndexError: string index out of range, can't figure out whyIndexError:字符串索引超出范围,不知道为什么
【发布时间】:2015-12-26 18:18:05
【问题描述】:

我希望在我的这部分代码中,删除从读取文件中获得的单词中的任何非字母符号。

我知道可能有一个空字符串正在测试,错误正在发生,

但我不知道为什么在我尝试了许多不同的代码之后。

这就是我现在所拥有的:

for i in given_file:

    cut_it_out = True

    while cut_it_out:
        if len(i) == 0:
            cut_it_out = False
        else:
            while (len(i) != 0) and cut_it_out:
                if i.lower()[0].isalpha() and i.lower()[len(i) - 1].isalpha():
                    cut_it_out = False

                if (not i.lower()[len(i) - 1].isalpha()):
                    i = i[:len(i) - 2]
                if (not i.lower()[0].isalpha()):
                    i = i[1:]

谁能帮我解决这个问题? 谢谢。

感谢有趣的答案 :),我希望它更精确,但是我似乎无法摆脱一个无限循环问题。

谁能帮我弄清楚?

all_words = {} # New empty dictionary
for i in given_file:
    if "--" in i:
        split_point = i.index("--")
        part_1 = i[:split_point]
        part_2 = i[split_point + 2:]
        combined_parts = [part_1, part_2]

        given_file.insert(given_file.index(i)+2, str(part_1))
        given_file.insert(given_file.index(part_1)+1, str(part_2))
        #given_file.extend(combined_parts)
        given_file.remove(i)
        continue


    elif len(i) > 0:
        if i.find('0') == -1 and i.find('1') == -1 and i.find('2') == -1 and i.find('3') == -1 and i.find('4') == -1\
            and i.find('5') == -1 and i.find('6') == -1 and i.find('7') == -1 and i.find('8') == -1 and i.find('9') == -1:
            while not i[:1].isalpha():
                i = i[1:]

            while not i[-1:].isalpha():
                i = i[:-1]

            if i.lower() not in all_words:
                all_words[i.lower()] = 1 
            elif i.lower() in all_words:
                all_words[i.lower()] += 1

【问题讨论】:

    标签: string loops python-3.x indexing


    【解决方案1】:

    我认为您的问题是解决方案过于复杂的结果。 @tobias_k 指出了错误。无论如何,您的代码可能非常低效。 尽量简化,比如试试:(我还没测试过)

    for i in given_file:
        beg=0
        end=len(i)-1
        while beg<=end and not i[beg].isalpha():
            beg=beg+1
        while beg<=end and not i[end].isalpha():
            end=end-1
        res=""
        if beg<=end:
           res=i[beg:end]
    

    【讨论】:

      【解决方案2】:

      您的代码存在一些问题:

      • 直接的问题是第二个if 可以去掉所有非字母字符组成的字符串中的最后一个字符,然后第三个if 会产生异常。
      • 如果最后一个字符不是字母,则去掉最后 两个 个字符。
      • 不需要这两个嵌套循环,您可以使用break 代替那个布尔变量
      • 如果i.lower()[x] 是非alpha,那么i[x] 也是;另外,最好使用i[-1] 作为最后一个索引

      在解决了这些问题后,但总体思路保持不变,您的代码变为

      while len(i) > 0:
          if i[0].isalpha() and i[-1].isalpha():
              break
          if not i[-1].isalpha():
              i = i[:-1]
          elif not i[0].isalpha(): # actually, just 'else' would be enough, too
              i = i[1:]
      

      但这仍然有点难以理解。我建议对字符串的两端使用两个循环:

      while i and not i[:1].isalpha():
          i = i[1:]
      while i and not i[-1:].isalpha():
          i = i[:-1]
      

      或者你可以只使用regular expression,这样想:

      i = re.sub(r"^[^a-zA-Z]+|[^a-zA-Z]+$", "", i)
      

      内容如下:替换组 a-zA-Z 中紧跟在字符串 (^) 或 (|) 开头之后的所有 (+) 字符,而不是 ([^...])字符串的结尾 ($) 和 ""

      【讨论】:

      • 感谢您的回答:)
      • 我希望它完美工作,所以我添加了更多内容,但现在它只是缺少一件完美的东西,但我被困在一堆无限循环中:/
      • 你能帮我看看问题是什么,如果我能提高效率吗?谢谢
      • 感谢您的努力 :)
      • 如果对代码有任何疑问,可以问我,我会尽力帮助使其易于理解
      猜你喜欢
      • 1970-01-01
      • 2021-01-30
      • 1970-01-01
      • 1970-01-01
      • 2014-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多