因此,该文件有大约 57,000 个书名、作者姓名和一个 ETEXT 编号。我正在尝试解析该文件以仅获取 ETEXT 编号
文件是这样的:
TITLE and AUTHOR ETEXT NO.
Aspects of plant life; with special reference to the British flora, 56900
by Robert Lloyd Praeger
The Vicar of Morwenstow, by Sabine Baring-Gould 56899
[Subtitle: Being a Life of Robert Stephen Hawker, M.A.]
Raamatun tutkisteluja IV, mennessä Charles T. Russell 56898
[Subtitle: Harmagedonin taistelu]
[Language: Finnish]
Raamatun tutkisteluja III, mennessä Charles T. Russell 56897
[Subtitle: Tulkoon valtakuntasi]
[Language: Finnish]
Tom Thatcher's Fortune, by Horatio Alger, Jr. 56896
A Yankee Flier in the Far East, by Al Avery 56895
and George Rutherford Montgomery
[Illustrator: Paul Laune]
Nancy Brandon's Mystery, by Lillian Garis 56894
Nervous Ills, by Boris Sidis 56893
[Subtitle: Their Cause and Cure]
Pensées sans langage, par Francis Picabia 56892
[Language: French]
Helon's Pilgrimage to Jerusalem, Volume 2 of 2, by Frederick Strauss 56891
[Subtitle: A picture of Judaism, in the century
which preceded the advent of our Savior]
Fra Tommaso Campanella, Vol. 1, di Luigi Amabile 56890
[Subtitle: la sua congiura, i suoi processi e la sua pazzia]
[Language: Italian]
The Blue Star, by Fletcher Pratt 56889
Importanza e risultati degli incrociamenti in avicoltura, 56888
di Teodoro Pascal
[Language: Italian]
这是我尝试过的:
def search_by_etext():
fhand = open('GUTINDEX.ALL')
print("Search by ETEXT:")
for line in fhand:
if not line.startswith(" [") and not line.startswith("~"):
if not line.startswith(" ") and not line.startswith("TITLE"):
words = line.rstrip()
words = line.lstrip()
words = words[-7:]
print (words)
search_by_etext()
好吧,代码大部分都能正常工作。但是,对于某些行,它会给我部分标题或其他内容。喜欢: 这种输出(),包含'decott',这是作者姓名的一部分,不应该在这里。 2
为此: 害羞的地震,作者:奥利弗·赫尔福德 56765 [副标题:和其他寓言和诗句]
乔治·斯特林 (George Sterling) 的兰花之家和其他诗歌 56764
意大利北部民谣,作者:Alice Vansittart Strettel Carr 56763 和伦道夫·凯迪克 [副标题:城乡生活速写]
新西兰的野生动物。第 1 部分,哺乳动物,作者:George M. Thomson 56762 [副标题:新西兰科学与艺术委员会,手册第 2 号]
Universal Brotherhood,第 13 卷,第 10 期,1899 年 1 月,Various 56761 着
De drie steden: Lourdes, door Émile Zola 56760 [语言:荷兰语]
另一个例子:
为了 Rhandensche Jongens,门 Jan Lens 56702 [插画家:Tjeerd Bottema] [语言:荷兰语]
The Story of The Woman's Party,作者 Inez Haynes Irwin 56701
摩门教教义简单明了,作者 Charles W. Penrose 56700 [副标题:或生命之树的叶子]
Burkamukk 的石斧,作者:Mary Grant Bruce 56699 [插画家:J. Macfarlane]
The Latter-Day Prophet,作者:George Q. Cannon 56698 [副标题:为年轻人写的约瑟·斯密史]
这里:生活]不应该在那里。以空格开头的行已被解析出来:
if not line.startswith(" [") and not line.startswith("~"):
但我仍然在我的输出结果中得到这些关闭值。
请您参考如下方法:
简单的解决方案:正则表达式来拯救!
import re
with open("etext.txt") as f:
for line in f:
match = re.search(r" (\d+)$", line.strip())
if match:
print(match.group(1))
正则表达式 (\d+)$ 将匹配“至少一个空格后跟字符串末尾的 1 个或多个数字”,并且只捕获“一个或多个数字”组.
您最终可以改进正则表达式 - 即,如果您知道所有电子文本代码的长度正好为 5 位,则可以将正则表达式更改为 (\d{5})$。
这适用于您发布的示例文本。如果它不能在您自己的文件上正常工作,那么我们需要足够的真实数据来找出您真正拥有的东西。
