Python中同一行中的所有数据变量

Python中同一行中的所有数据变量,python,csv,row,Python,Csv,Row,我有一个脚本,它使用从特定路径中的文本提取的数据创建一个csv。尽管RegEx上可能存在错误,但它主要提取部分文本,并将其保存在变量中,而printa保存在csv中。每个公司在此csv中必须有一行。这样,当csv打开时,公司数量和所有信息都可以通过变量可视化 我的问题是,当我看到CSV调用时,在本例中,所有公司1,数据不放在同一行中,它们跳转 此外,标题重复,我不希望他们重复自己 首先尝试将csvFile的模式从append改为w write,还要检查您实际使用的编辑器是否使用逗号作为csv文件

我有一个脚本,它使用从特定路径中的文本提取的数据创建一个csv。尽管RegEx上可能存在错误,但它主要提取部分文本,并将其保存在变量中,而printa保存在csv中。每个公司在此csv中必须有一行。这样,当csv打开时,公司数量和所有信息都可以通过变量可视化

我的问题是,当我看到CSV调用时,在本例中,所有公司1,数据不放在同一行中,它们跳转

此外,标题重复,我不希望他们重复自己


首先尝试将csvFile的模式从append改为w write,还要检查您实际使用的编辑器是否使用逗号作为csv文件的列分隔符,因为在上图中,编辑器似乎将逗号视为普通字符

在打印字符串之前,还要从字符串中删除任何回车符\n\r,这可以通过以下代码完成

csvData=[strdata.replace'\n',.replace'\r',用于csvData中的数据]

注:
如果有任何可能,csv文件中两个元素之间的空行可能会出现问题,可以通过将打开的'All_Companies1.csv','a'as csvFile更改为打开的'All_Companies1.csv','a',newline=as csvFile

尝试使用pandas来解决。您可以在一行代码中完成所有操作。pandas.read_csv see doc我使用的编辑器使用逗号作为csv的分隔符,这不是问题所在。我已经按照你告诉我的做了,它确实有效,但是标题是由公司重复的,或者更确切地说,是每行重复的。问题是,在使用数据操作之前,我正在替换“\n”,以便能够调试它们,但在CSV中输入格式时,我没有保存格式。除此之外,现在CSV在我创建一个公司的新迭代的每一行都重复标题。此外,我还有另一个问题,但与正则表达式有关。当我打印company_name的值时,大多数公司的输出是。当我将正则表达式放入另一个没有迭代的脚本中时,它工作正常。为什么会这样?我怎样才能解决这个问题?此外,在另一个正则表达式中也会发生。。。但在更大程度上,只有在公司变量的名称中:company_name我提出了另一个问题,它与最后一个问题的关系是SRE_Match和convert to string。谢谢你的回答@巴拉哈希什
# coding=utf-8
# Libreria RegEx de Python.
import re
# Libreria para rutas.
import os
import csv

# function betwwen: return the value between two words a and b
def between(value, a, b):
    pos_a = value.find(a)  # Find and validate before-part.
    if pos_a == -1: return ""  # Find and validate after part.
    pos_b = value.rfind(b)
    if pos_b == -1: return ""  # Return middle part.
    adjusted_pos_a = pos_a + len(a)
    if adjusted_pos_a >= pos_b: return ""
    return value[adjusted_pos_a:pos_b]

# function scan folder DiarioOficial
def scan_folder():
    # directory 'path'
    path = '/Users/anna/PycharmProjects/extractData/DiarioOficial'
    # contador de ficheros del path
    count = 0

    # creation csv as csvFile
    with open('All_Companies1.csv', 'a') as csvFile:
        # iterate all paths in the folder DiarioOficial without name
        for (path, dirnames, file_names) in os.walk(path):
            # iterate over all the files in the path (+ file_name)
            for file_name in file_names:
                # Add extension that is required
                if file_name.endswith(".txt"):
                    # summatory count files in DiarioOficial folder
                    count = count + 1
                    # concatenation path + file name
                    file_path=os.path.join(path, file_name)
                    #print(file_path)
                    # open and read the file path
                    mensaje = open(file_path).read()
                    # Replace a newline for a space
                    mensaje = mensaje.replace("\n","")

                    # Company Name
                    keywords_cap = ['SpA', 'SPA', 'LIMITADA', 'LTDA', 'S.A.', 'E.I.R.L.', 'S.L.']
                    # re.escape to solve the problem with metacharacters in keyword_obj
                    keywords_cap = map(re.escape, keywords_cap)
                    # sorting the items by lengh in descending order
                    keywords_cap.sort(key=len, reverse=True)
                    obj = re.compile(r'[:,;.]\s*"?([^:,;.]*?(?<!\w)(?:{}))'.format('|'.join(keywords_cap)))
                    if obj:
                        # To obtain the first match obj.search(mensaje).group(1)
                        company_name = obj.search(mensaje)
                    else:
                        company_name = "None"

                    # CVE Number of the file
                    regex = r"\s*CVE\s+([^|]*)"
                    matches = re.search(regex, mensaje)
                    if matches:
                        company_cve = matches.group(1).strip()
                    else:
                        company_cve = "None"

                    # Section of diariooficial.interior.gob.cl
                    company_sect = between(mensaje, 'SECCIÓN', 'Núm.')
                    if company_sect:
                        company_sect = company_sect
                    else:
                        company_sect = "None"

                    # Name of the person that constitutes the company
                    company_ceo = re.search(r'\sante mí,\s+([^,]*)', mensaje)
                    if company_ceo:
                        company_ceo = company_ceo.group(1)
                    else:
                        company_ceo = "None"

                    # File Number from Section
                    num_reg = r'\sNúm.\s+([^|]*)'
                    match_num = re.search(num_reg, mensaje)
                    if match_num:
                        company_numsect = match_num.group(1)
                    else:
                        company_numsect = "None"

                    # Social Capital ($)
                    cap = r"\s*(CAPITAL:\s+([^-]*)|Capital social:\s+([^-]*)|Capital:\s+([^-]*)|Capital:\s+([^,]*))"
                    caps = re.search(cap, mensaje)
                    if caps:
                        company_capital = caps.group()
                    else:
                        company_capital = 'None'

                    csvData = [company_name, company_cve, company_sect, company_ceo, company_numsect, company_capital]
                    headers = ['COMPANY NAME', 'CVE', 'SECTION','CEO NAME','NUMBER SECTOR','COMPANY CAPITAL']
                    writer = csv.writer(csvFile, delimiter=',') # create a csv delimited by comma
                    writer.writerow(headers)  # print the header row
                    writer.writerow(csvData)  # print the Data in csv
            # Number of txt files
            print (count)
scan_folder()