提取开始标记和结束m之间的所有字符串

2024-05-21 07:41:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个从txt文件读取的单行字符串(文件只有这个字符串),格式如下:

[[“抽象”,“普通”,“参考”,“简介”,“动机”],[“真实”,“白天”,“晚上”,“二十”,“血”,“卡车”,“少校”,“船”,“飞机”],[“武器”,“枪”,“核”,“左轮手枪”],[“玫瑰”,“公主”,“花”,“美女”,“向日葵”,“士兵”,“想象”,“茉莉花”],[“布”,“衬衫”,“牛仔裤”,“裤子”]]

我要检索start marker=[”和end marker=“]之间的所有文本内容

所以我想要的输出应该是(新行分开):

“摘要”,“一般”,“参考”,“简介”,“动机”

“真的”,“白天”,“晚上”,“二十”,“血”,“卡车”,“少校”,“轮船”,“飞机”

“武器”,“枪”,“核武器”,“左轮手枪”

“玫瑰”,“公主”,“花朵”,“美人”,“向日葵”,“士兵”,“想象中的”,“茉莉花”

“布”,“衬衫”,“牛仔裤”,“裤子”

我编写了以下代码:

def fileRead(fpath):

    f = open(fpath, "r")

    for s in f:

            start = s.find('["')

            start += 1  # skip the bracket, move to the next character

            end = s.find('"]', start)

            print(s[start:end])

            return s[start:end]

但它只给我以下输出:

“摘要”,“一般”,“参考”,“简介”,“动机”

请让我知道什么需要更改以获得所需的输出?你知道吗


Tags: 文件字符串startend动机想象向日葵武器
3条回答

你可以试试这个代码

def fileRead(fpath):
    f = open(fpath, "r")
    s=f.read()
    while (s.find('["')!=-1 and s.find('"]')!=-1):
        g=min(s.find('["'),s.find('"]'))
        s=s[:g]+s[g+2:]
    s=s[1:-2]
    f.close()
    return s

我希望我是有用的

文字评估是完美的。它基本上获取一个表示为字符串的列表,并给出python列表

a = """["hello"]"""
b = literal_eval(a)
b[0]
>>> "hello" 

对于你的情况:

from ast import literal_eval


def fileRead(fpath):

    f = open(fpath, "r")
    f_string = f.readlines()
    f_list = literal_eval(f_string)
    print(f_list)
    for item in f_list:
        print(" ".join(item)) # joins words with space between them

Here是文档。你知道吗

这是一个正则表达式解决方案

import re
s = '[["abstract", "common", "reference", "introduction", "motivation"], ["real", "day", "night", "twenty", "blood", "truck", "major", "ship", "plane"], ["weapon", "guns", "nuclear", "revolver"], ["rose", "princess", "flower", "beauty", "sunflower", "soldier", "imaginary", "jasmine"], ["cloth", "shirt", "jeans", "trouser"]]'

s = re.compile(']\s*,').sub('\n',s) # Line feed
s = re.compile('\[|\]').sub('',s) # Remove []
print (s)

相关问题 更多 >