从Python中的字符串列表中删除章节号

2024-06-01 07:51:35 发布

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

im编写的程序将字符串列表作为输入,并试图删除章节号。我已经写了这个函数,但它现在不起作用。我已经提供了我的函数和输出的示例!谢谢您!你知道吗

def remove_chapter(chapter_header):
    for i in range(101):
        chapters="Chapter " + str(i)
        chapter_text=[my_string.replace(chapters,"") for my_string in chapter_header]
    return chapter_text

以下是不工作功能的电流输出: Output


Tags: 函数字符串textin程序示例列表for
2条回答

因为你的strings有一个相似的模式需要删除,但是有一些变化(chapter number),所以最好使用^{}。有了它,你的pattern matching就有了很大的灵活性。你知道吗

所以,你需要做的就是:

>>> import re
>>> [ re.sub('Chapter \d+ ', '', string) for string in chapter_header ]

#驱动程序值:

IN : chapter_header = ['Chapter 1 It is ...','However little ...','Chapter 12 Lorem Ipsum']

OUT : ['It is ...', 'However little ...', 'Lorem Ipsum']

把它分解,你的模式看起来像:

'Chapter'<whitespace>[number/s]<whitespace>

因此,只要找到这个模式,字符串就会被替换,如果找不到,就被忽略。你知道吗

给出一个章节列表,我们可以把章节和数字放到每章的第一个单词。你知道吗

给定的

import itertools as it


chapters = [
    "Chapter 1  It is a truth universally acknowledged ...",
    "Chapter 2  Mr. Bennet was among the earliest ...",
    "Chapter 3  Not all that Mrs. Bennet, however, with ...",
]

代码

pred = lambda x: (x == "Chapter") or x.isdigit() 
results = [list(it.dropwhile(pred, [word for word in chapter.split()])) for chapter in chapters]
results 

输出

[['It', 'is', 'a', 'truth', 'universally', 'acknowledged', '...'],
 ['Mr.', 'Bennet', 'was', 'among', 'the', 'earliest', '...'],
 ['Not', 'all', 'that', 'Mrs.', 'Bennet,', 'however,', 'with', '...']]

细节

列表理解将章节分为列表和列表中的单词。等价地:

for chapter in chapters:
    print([word for word in chapter.split()])

# ['Chapter', '1', 'It', 'is', 'a', 'truth', 'universally', 'acknowledged', '...']
# ['Chapter', '2', 'Mr.', 'Bennet', 'was', 'among', 'the', 'earliest', '...']
# ['Chapter', '3', 'Not', 'all', 'that', 'Mrs.', 'Bennet,', 'however,', 'with', '...']

最后,^{}迭代每个列表并删除项,直到谓词不再为true。换言之,将项目一直放到既不是"Chapter"也不是数字的第一个。你知道吗

如果需要,生成的章节可以作为字符串重新连接。你知道吗

[" ".join(chapter) for chapter in results]
# ['It is a truth universally acknowledged ...',
#  'Mr. Bennet was among the earliest ...',
#  'Not all that Mrs. Bennet, however, with ...']

相关问题 更多 >