【问题标题】:Finding words that start with character will fail with new line查找以字符开头的单词将失败并换行
【发布时间】:2013-11-06 16:42:21
【问题描述】:

我正在尝试编写一个在推文中突出显示主题标签的程序。但是如果推文包含一个新行,程序将失败,如果它只有一行,程序将工作。为什么数据中有新行时会失败?我收到错误index out of range

def highlight(data):
    for word in data.split(" "):
        if word[0] == "#":
            print "<FONT COLOR=\"brown\">" + word + "</FONT>",
        else:
            print word,

highlight("""hello world this
    is a #test that i am #writing.""")

【问题讨论】:

    标签: python string hashtag


    【解决方案1】:

    此代码将起作用:

    def highlight(data):
        for word in data.split():
            if word[0] == "#":
                print "<FONT COLOR=\"brown\">" + word + "</FONT>",
            else:
                print word,
    
    highlight("""hello world this
        is a #test that i am #writing.""")
    

    这将用换行符和空格分割文本。

    【讨论】:

      【解决方案2】:

      因为换行会使data.split(" ") 包含''s。您正在尝试获取其中的第一个元素,并且:

      In [4]: ''[0]
      ---------------------------------------------------------------------------
      IndexError                                Traceback (most recent call last)
      <ipython-input-4-6f70a0cbdc74> in <module>()
      ----> 1 [][0]
      
      IndexError: list index out of range
      
      In [6]: a = """
         ...: hello world this
         ...:     is a #test that i am #writing."""
      
      In [7]: a.split(' ')
      Out[7]:
      ['\nhello',
       'world',
       'this\n',
       '',
       '',
       '',
       'is',
       'a',
       '#test',
       'that',
       'i',
       'am',
       '#writing.']
      

      只需将其更改为 data.split() 即可。

      【讨论】:

        【解决方案3】:

        在推文第二行的开头,有四个空格。

        """test
            other_test""" == "test\n    other_test"
        

        所以如果你用空格分割那个字符串,你会得到三个空字符串。

        >>> "test\n    other_test".split(" ")
        ['test\n', '', '', '', 'other_test']
        

        现在如果您尝试访问字符串'' 的第一个字符,则字符索引超出范围。

        为防止出现此错误,请使用data.split() 或检查当前字符串是否为空。

        【讨论】:

          【解决方案4】:

          确保您首先有一个“单词”:

          def highlight(data):
              for word in data.split(" "):
                  if word and word[0] == "#":
                      print "<FONT COLOR=\"brown\">" + word + "</FONT>",
                  else:
                      print word,
          

          以后在询问时,最好包含错误消息的全文。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2023-01-07
            • 1970-01-01
            • 2022-08-11
            • 2022-11-17
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多