python - 试图从文本文件中提取有用的信息 block

标签 python string

我正在尝试使用字符串切片从文本文件中提取某个表的所有出现,但它总是一遍又一遍地提取第一个切片。

也许我需要一个用于开始和结束计数的虚拟变量?

result = ''  
start = 'start of stuff I want'  
end = 'end of stuff I want'  
otn = o.read()  
count = otn.count(start)  
s = 0  
e = 0  
for i in range(count):  
    s = otn.find(start, s)  
    e = otn.find(end, s)  
    result = result + otn[s:e]  
print(result)  

有什么建议吗?

最佳答案

试试这个。它更像 python-y 并且可重用:

def extract_delimited_data(data, begin_delimiter, end_delimiter):
    s = data.find(begin_delimiter)

    while s != -1:
        e = data.find(end_delimiter, s + len(begin_delimiter))

        s += len(begin_delimiter)
        yield data[s:e]

        s = data.find(begin_delimiter, e + len(end_delimiter))

data = 'foo<bar>hello<world>'

print list(extract_delimited_data(data, '<', '>'))

输出:

['bar', 'world']

关于python - 试图从文本文件中提取有用的信息 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6765502/

相关文章:

c# - 我如何确定在我的 2048 实现中移动和合并了哪些图 block ?

c++ - 比较 wstring 和忽略大小写

c - c语言如何在动态数组中添加/删除字符串

python - 使用 Python 将 XML 转为 MYSQL

没有逗号的Python打印

python - Pandas groupby 箱线图上的轴错误

python - 确定以下编码段的时间复杂度

python - 如何将特定月份值与 pandas 数据框中的日期相加?

java - 将空对象转换为字符串

python - 如果该字符串包含子字符串,则从列表中获取字符串