Python的文本提取

问题描述 投票:2回答:2

我正在与Python文本提取。输出并不像期望的,因为我希望它!

我有一个包含这样的信息的文本文件:

FN Clarivate Analytics Web of Science
VR 1.0

PT J

AU Chen, G

   Gully, SM

   Whiteman, JA

   Kilcullen, RN

AF Chen, G

   Gully, SM

   Whiteman, JA

   Kilcullen, RN

TI Examination of relationships among trait-like individual differences,

   state-like individual differences, and learning performance

SO JOURNAL OF APPLIED PSYCHOLOGY

CT 13th Annual Conference of the

   Society-for-Industrial-and-Organizational-Psychology

CY APR 24-26, 1998

CL DALLAS, TEXAS

SP Soc Ind & Org Psychol

RI Gully, Stanley/D-1302-2012

OI Gully, Stanley/0000-0003-4037-3883

SN 0021-9010

PD DEC

PY 2000

VL 85

IS 6

BP 835

EP 847

DI 10.1037//0021-9010.85.6.835

UT WOS:000165745400001

PM 11125649

ER

当我用我这样的代码

import random
import sys

filepath = "data\jap_2000-2001-plain.txt"

with open(filepath) as f:
    articles = f.read().strip().split("\n")

articles_list = []

author = ""
title = ""
year = ""
doi = ""

for article in articles:
    if "AU" in article:
        author = article.split("#")[-1]
    if "TI" in article:
        title = article.split("#")[-1]
    if "PY" in article:
        year = article.split("#")[-1]
    if "DI" in article:
        doi = article.split("#")[-1]
    if article == "ER#":
        articles_list.append("{}, {}, {}, https://doi.org/{}".format(author, title, year, doi))
print("Oh hello sir, how many articles do you like to get?")
amount = input()

random_articles = random.sample(articles_list, k = int(amount))


for i in random_articles:
    print(i)
    print("\n")

exit = input('Please enter exit to exit: \n')
if exit in ['exit','Exit']:
    print("Goodbye sir!")
    sys.exit()

提取不包括断行后,已输入的数据,如果我运行此代码,输出将看起来像“AU陈,G”,不包括其他的名字,相同的标题等等等等。

我的输出如下:

陈,性状之间的关系的G.考试,2000年,doi.dx.10.1037 // 0021-9010.85.6.835

所需的输出应为:

陈,G.,沟壑,SM,怀特曼,JA,基尔卡伦,RN。,2000,性状类似的个体差异,类似于国家的个体差异和学习表现,doi.dx.10.1037 // 0021之间的关系的考试-9010.85.6.835

但提取仅包括每行中的第一行 -

有什么建议么?

python string extraction
2个回答
1
投票

你需要跟踪你在哪个部门,你正在分析文件。有写状态机更清洁的方式,但作为一个快速和简单的例子,你可以做类似下面。

基本上,每个部分中的所有行添加到列表中该节,然后再结合清单,做任何结尾。请注意,我没有测试这一点,只是伪编码向您展示的总体思路。

authors = []
title = []
section = None

for line in articles:
    line = line.strip()

    # Check for start of new section, select the right list to add to
    if line.startswith("AU"):
        line = line[3:]
        section = authors
    elif line.startswith("TI"):
        line = line[3:]
        section = title
    # Other sections..
    ...

    # Add line to the current section
    if line and section is not None:
        section.append(line)

authors_str = ', '.join(authors)
title_str = ' '.join(title)
print authors_str, title_str

0
投票

初步认识

根据你的榜样,我认为:

  • 文本以行提供。
  • 该示例文本显示有太多的换行符,可能它从DOS / Windows的被迁移的神器?如果是的话,则需要要么CRLF处理,或交替行应该被忽略。
  • 的线被划分为几个部分。
  • 每个部分是由在节中的第一行的列0,1两个字母的大写字母标记分隔,并一直持续到新的一节的开始。
  • 每行有任一个标签或2个空白,接着是空白,在列0-2。
  • 通过标签ER分隔人造节标志着结束的纪录。
  • ER部分不包含可用的文本。

它也可能是这样:

  • 记录由FN标签开始。
  • FN / ER对外面遇到的任何文字可以忽略不计。

建议设计

如果这是真的,我建议你写的使用逻辑文本处理器:

  • 读线。
  • 处理CR / LF处理;或跳过交替行;或“不担心真正的文本没有这些换行符”?
  • 使用状态机与数目不详的状态,处于初始状态ER
  • 特殊规则:直到遇到ER线忽略了FN状态的文本。
  • 一般规则:当标签被看到,结束之前的状态,并开始在看到标签的名字命名的新状态。中积累的所有文本添加到该记录。
  • 如果没有标签看到,堆积在先前的标记文本。
  • 特殊规则:在进入ER状态时,累计的记录添加到累积记录列表。

在这个过程结束时,你将有一个记录列表,具有多种累积的标签。然后,您可以处理各种方式的标签。

事情是这样的:

from warnings import warn

Debug = True

def read_lines_from(file):
    """Read and split lines from file. This is a separate function, instead
       of just using file.readlines(), in case extra work is needed like
       dos-to-unix conversion inside a unix environment.
    """
    with open(file) as f:
        text = f.read()
        lines = text.split('\n')

    return lines

def parse_file(file):
    """Parse file in format given by 
        https://stackoverflow.com/questions/54520331
    """
    lines = read_lines_from(file)
    state = 'ER'
    records = []
    current = None

    for line_no, line in enumerate(lines):
        tag, rest = line[:2], line[3:]

        if Debug:
            print(F"State: {state}, Tag: {tag}, Rest: {rest}")

        # Skip empty lines
        if tag == '':
            if Debug:
                print(F"Skip empty line at {line_no}")
            continue

        if tag == '  ':
            # Append text, except in ER state.
            if state != 'ER':
                if Debug:
                    print(F"Append text to {state}: {rest}")
                current[state].append(rest)
            continue

        # Found a tag. Process it.

        if tag == 'ER':
            if Debug:
                print("Tag 'ER'. Completed record:")
                print(current)

            records.append(current)
            current = None
            state = tag
            continue

        if tag == 'FN':
            if state != 'ER':
                warn(F"Found 'FN' tag without previous 'ER' at line {line_no}")
                if len(current.keys()):
                    warn(F"Previous record (FN:{current['FN']}) discarded.")

            if Debug:
                print("Tag 'FN'. Create empty record.")

            current = {}

        # All tags except ER get this:
        if Debug:
            print(F"Tag '{tag}'. Create list with rest: {rest}")

        current[tag] = [rest]
        state = tag

    return records

if __name__ == '__main__':
    records = parse_file('input.txt')
    print('Records =', records)
© www.soinside.com 2019 - 2024. All rights reserved.