使用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

最佳答案

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

然后使用split(...)[1]获得标记后的零件

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

关于python - 使用Python 2.7在出现字符串的位置拆分文本文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19236833/

10-10 21:17