首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >为什么我得到TypeError:序列项0:预期的str实例,列表找到

为什么我得到TypeError:序列项0:预期的str实例,列表找到
EN

Stack Overflow用户
提问于 2022-06-09 09:28:37
回答 1查看 79关注 0票数 -4

因此,出于某种原因,这个问题突然出现了,我不知道为什么会发生。

当我改变了打开文件的方式之后,它就开始出现了,但是我一点也不知道为什么会影响它,因为对象不像.我已经想了大概一个小时了,但没有结果。

代码语言:javascript
复制
import re

def get_words_from_file(filename):
    """gets words from file and applies reg expression (brokey)"""
    with open(filename, 'r', encoding="utf-8") as file:
        all_lines = [line.strip() for line in file]

    bound_start = 0
    bound_end = 0
    bound_num = 0

    for line in all_lines:
        bound_num = bound_num + 1
        if "*** START" in line:
            bound_start = bound_num
        elif "*** END" in line:
            bound_end = bound_num
        else:
            pass
    print(bound_start, bound_end)


    bound_num = 0
    pre_re_list = []
    for line in all_lines:
        bound_num = bound_num + 1
        if bound_num in range(bound_start, bound_end):
            pre_re_list.append(line)
        else:
            pass
    print(pre_re_list)

    bound_num = 0
    final_list = []
    for j in pre_re_list:
        
        word_on_line = re.findall("[a-z]+[-'][a-z]+|[a-z]+[']?|[a-z]+", pre_re_list[bound_num])
        bound_num = bound_num + 1
        final_list.append(word_on_line)
        

    return final_list


filename = "abc.txt"
words2 = get_words_from_file(filename)
print(filename, "loaded ok.")
print("{} valid words found.".format(len(words2)))
print("Valid word list:")
print("\n".join(words2))

我开始收到这条错误消息,如果有人能告诉我为什么/如何修复它,那就太好了:

代码语言:javascript
复制
abc.txt loaded ok.
2 valid words found.
Valid word list:
*** RUN TIME ERROR(S) ***
Traceback (most recent call last):
  File "__source.py", line 50, in <module>
    print("\n".join(words2))
TypeError: sequence item 0: expected str instance, list found
EN

回答 1

Stack Overflow用户

发布于 2022-06-10 03:19:26

当你使用re。就像这里的word_on_line = re.findall("[a-z]+[-'][a-z]+|[a-z]+[']?|[a-z]+", pre_re_list[bound_num],您不能直接将列表插入表达式,首先必须将其转换为字符串。希望这能有所帮助

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72557879

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档