索引错误,代码未正确拆分我的字符串

Index error, code not splitting my string properly

我正在尝试 运行 pytest 来测试我的函数,但我 运行 遇到了一个问题,我试图拆分一个名为 get_prepositional_phrase(amount) 的函数 returns 将三个变量的字符串放入每个变量中,但在我拆分它之后,我不断得到一个列表索引超出范围的错误

我要拆分的字符串的代码是:

phrase = (f'{connect} {determiner2} {noun2}')

下面是我的测试功能代码。

def test_get_prepositional_phrase():
    phrase1 = get_prepositional_phrase(1)

prep = ["about", "above", "across", "after", "along",
    "around", "at", "before", "behind", "below",
    "beyond", "by", "despite", "except", "for",
    "from", "in", "into", "near", "of",
    "off", "on", "onto", "out", "over",
    "past", "to", "under", "with", "without"]


for word in phrase1:
    parts = word.split()
    one = parts[0]
    # two = parts[1]
    # three = parts[2]

for _ in range(30):
    connector = get_preposition()
assert one in connector

如果 parts 列表中只有一个(或零个)项目,第 115 行将引发异常。鉴于您的代码是

one = parts[1]
# two = parts[1]
# three = parts[2]

我会说你应该将 parts[0],而不是 parts[1],分配给 one。此外,一个好的规则是首先检查所有必需的 pre-conditions。这将涉及:

assert type(phrase1) is list                   # Is list.
assert len(phrase1) >= 2                       # Minimum size.
assert(all([type(x) is str for x in phrase1])) # All items are string.
for word in phrase1:
    pass # Guaranteed safe to use word[1] as a string here.

无论如何,您的短语构造为:

f'{connect} {determiner2} {noun2}'

表示它是单个字符串而不是单词列表。这意味着:

for word in phrase1:      # One character at a time.
    parts = word.split()  # One-element list with that character.
    one = parts[1]        # NO !

总是给你一个single-character字串,因此parts将永远是一个包含[=43]的one-element列表=] 字符串。因此 parts[1] 表达式将失败。

您需要的是:

for word in phrase1.split(): # One word at a time.
    one = word[0]
    # two = word[1]
    # three = word[2]

底线:for i in a_string 给出字符串的每个字符,而 for i in a_list_of_strings 给出列表中的每个字符串。