1

使用 Python,如何在特定字符串出现的位置拆分文本文件?

我尝试使用.split()但它给出了一个错误:AttributeError: 'file' object has no attribute 'split'

代码:

book = open('finn.txt')
x = book.split('*** START OF THIS PROJECT GUTENBERG EBOOK HUCKLEBERRY FINN ***')

文件:finn.txt

Title: Adventures of Huckleberry Finn, Complete

Author: Mark Twain (Samuel Clemens)


*** START OF THIS PROJECT GUTENBERG EBOOK HUCKLEBERRY FINN ***

Produced by David Widger

期望的输出

Produced by David Widger
4

1 回答 1

6

您可以使用read()将整个文件读入字符串

然后使用split(...)[1]在你的标记之后获取部分

book = open('finn.txt').read()
x = book.split('*** START OF THIS PROJECT GUTENBERG EBOOK HUCKLEBERRY FINN ***')[1]
于 2013-10-08T00:00:03.177 回答