查找以字符开头的单词将失败并换行

问题描述 投票:0回答:5

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

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
5个回答
2
投票

此代码将起作用:

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.""")

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


1
投票

因为换行符会使

data.split(" ")
包含
''
。您正在尝试获取其中的第一个元素,并且,嗯:

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()
就可以了。


1
投票

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

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

因此,如果您用空格分割该字符串,您将得到三个空字符串。

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

现在,如果您尝试访问字符串的第一个字符

''
,则字符索引超出范围。

要防止此错误,请使用

data.split()
或检查当前字符串是否为空。


1
投票

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

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

将来询问时,包含错误消息的全文会有所帮助。


-3
投票

你好世界,这是一个测试我的堆栈溢出和装备流程 hashtak3#fdf

© www.soinside.com 2019 - 2024. All rights reserved.