如何使用Python在文本文件中查找所有isbn? [英] How to use Python to find all isbn in a text file?

查看:161
本文介绍了如何使用Python在文本文件中查找所有isbn?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本文件text_isbn,其中装有ISBN.我想编写一个脚本来对其进行解析,然后将其写入新的文本文件中,并在每个新行中添加每个ISBN号.

I have a text file text_isbn with loads of ISBN in it. I want to write a script to parse it and write it to a new text file with each ISBN number in a new line.

到目前为止,我可以编写用于查找ISBN的正则表达式,但无法进行进一步处理:

Thus far I could write the regular expression for finding the ISBN, but could not process any further:

import re
list = open("text_isbn", "r")
regex = re.compile('(?:[0-9]{3}-)?[0-9]{1,5}-[0-9]{1,7}-[0-9]{1,6}-[0-9]')

我尝试使用以下内容,但出现错误(我认为列表格式不正确...)

I tried to use the following but got an error (I guess the list is not in proper format...)

parsed = regex.findall(list)

如何进行解析并将其写入新文件(output.txt)?

How to do the parsing and write it to a new file (output.txt)?

这是text_isbn

Praxisguide Wissensmanagement - 978-3-540-46225-5
Programmiersprachen - 978-3-8274-2851-6
Effizient im Studium - 978-3-8348-8108-3

推荐答案

如何

import re

isbn = re.compile("(?:[0-9]{3}-)?[0-9]{1,5}-[0-9]{1,7}-[0-9]{1,6}-[0-9]")

matches = []

with open("text_isbn") as isbn_lines:
    for line in isbn_lines:
        matches.extend(isbn.findall(line))

这篇关于如何使用Python在文本文件中查找所有isbn?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆