Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用csv模块解析.txt文件中的文本_Python_Python 2.7_Parsing_Csv - Fatal编程技术网

Python 使用csv模块解析.txt文件中的文本

Python 使用csv模块解析.txt文件中的文本,python,python-2.7,parsing,csv,Python,Python 2.7,Parsing,Csv,我每天都会收到一封电子邮件,电子邮件的格式总是一样的,只是有些数据不同。我编写了一个VBA宏,将电子邮件导出到文本文件。现在它是一个文本文件,我想解析数据,以便只获取新信息 电子邮件的格式是这样的 > Irrelevant data > Irrelevant data > Type: YUK > Status: OPEN > Date: 6/22/2015 > Description: ---- > > Descripti

我每天都会收到一封电子邮件,电子邮件的格式总是一样的,只是有些数据不同。我编写了一个VBA宏,将电子邮件导出到文本文件。现在它是一个文本文件,我想解析数据,以便只获取新信息

电子邮件的格式是这样的

> Irrelevant data  
> Irrelevant data
> Type:     YUK
> Status:   OPEN
> Date:     6/22/2015
> Description: ----
> 
> Description blah blah blah
> Thank you
我想捕获相关数据。例如,在这种情况下,我只想捕捉YUK,OPEN,6/22/2015和描述等等。我尝试使用csv模块逐行打印这些行,但我似乎找不到解析这些信息的方法

这就是我目前所拥有的。不过,它只打印出行

import os
import glob
import csv

path = "emailtxt/"
glob = max(glob.iglob(path + '*.txt'), key=os.path.getctime)#most recent file located in the emailtxt
newestFile = os.path.basename(glob)#removes the emailtxt\ from its name

f = open(path+newestFile)

read = csv.reader(f)
for row in read:
    print row

f.close()

如何解析文本文件

我不认为您需要的是
csv
模块,只需常规文件I/O即可满足您的需要,即;逐行读取文件,并从每一行提取所需数据并将其存储在
列表中,例如:

import os
import glob

path = "emailtxt/"
glob = max(glob.iglob(path + '*.txt'), key=os.path.getctime)#most recent file located in the emailtxt
newestFile = os.path.basename(glob)          #removes the emailtxt\ from its name

capture_list = []                            #list to hold captured words
with open(path+newestFile, 'r') as f:        #open the file for reading
    for line in f:                           #Go line by line
        capture_list.append(line.split()[2]) #add to the list last word

我并不认为您需要的是
csv
模块,只是常规文件I/O可以满足您的需要,即;逐行读取文件,并从每一行提取所需数据并将其存储在
列表中,例如:

import os
import glob

path = "emailtxt/"
glob = max(glob.iglob(path + '*.txt'), key=os.path.getctime)#most recent file located in the emailtxt
newestFile = os.path.basename(glob)          #removes the emailtxt\ from its name

capture_list = []                            #list to hold captured words
with open(path+newestFile, 'r') as f:        #open the file for reading
    for line in f:                           #Go line by line
        capture_list.append(line.split()[2]) #add to the list last word

如果您能够单独打印出行,那么解析它们就是将行(表示为字符串)分开的问题。假设每个项目描述符后面都有一些空格,或者每个描述符后面都有一个冒号,您可以使用它来解析冒号和空格后面的任何内容。请参阅python字符串,以便能够在有用点拆分行


就实际解析数据而言,您可以执行一系列if语句来捕获每个状态或文件类型。对于日期,请尝试使用函数将日期计算为datetime对象。您所要做的就是匹配日期的格式,在您的情况下,该格式似乎是“%m/%d/%y”。

如果您能够单独打印出行,则解析它们就是将行(以字符串表示)分开的问题。假设每个项目描述符后面都有一些空格,或者每个描述符后面都有一个冒号,您可以使用它来解析冒号和空格后面的任何内容。请参阅python字符串,以便能够在有用点拆分行


就实际解析数据而言,您可以执行一系列if语句来捕获每个状态或文件类型。对于日期,请尝试使用函数将日期计算为datetime对象。您所要做的就是匹配日期的格式,在您的情况下,它似乎是“%m/%d/%y”。

使用正则表达式怎么样

def get_info(string_to_search):
    res_dict = {}
    import re

    find_type = re.compile("Type:[\s]*[\w]*")
    res = find_type.search(string_to_search)
    res_dict["Type"] = res.group(0).split(":")[1].strip()

    find_Status = re.compile("Status:[\s]*[\w]*")
    res = find_Status.search(string_to_search)
    res_dict["Status"] = res.group(0).split(":")[1].strip()

    find_date = re.compile("Date:[\s]*[/0-9]*")
    res = find_date.search(string_to_search)
    res_dict["Date"] = res.group(0).split(":")[1].strip()

    res_dict["description"] = string_to_search.split("Description:")[1].replace("Thank you","")
    return res_dict


search_string = """> Irrelevant data
> Irrelevant data
> Type:     YUK
> Status:   OPEN
> Date:     6/22/2015
> Description: ----
>
> Description blah blah blah
> Thank you
"""
info =  get_info(search_string)

print info
print info["Type"]
print info["Status"]
print info["Date"]
print info["description"]
输出:

{'Status': 'OPEN', 'Date': '6/22/2015', 'Type': 'YUK', 'description': ' ----\n>\n> Description blah blah blah\n> \n'}
YUK
OPEN
6/22/2015
 ----
>
> Description blah blah blah
> 

使用正则表达式怎么样

def get_info(string_to_search):
    res_dict = {}
    import re

    find_type = re.compile("Type:[\s]*[\w]*")
    res = find_type.search(string_to_search)
    res_dict["Type"] = res.group(0).split(":")[1].strip()

    find_Status = re.compile("Status:[\s]*[\w]*")
    res = find_Status.search(string_to_search)
    res_dict["Status"] = res.group(0).split(":")[1].strip()

    find_date = re.compile("Date:[\s]*[/0-9]*")
    res = find_date.search(string_to_search)
    res_dict["Date"] = res.group(0).split(":")[1].strip()

    res_dict["description"] = string_to_search.split("Description:")[1].replace("Thank you","")
    return res_dict


search_string = """> Irrelevant data
> Irrelevant data
> Type:     YUK
> Status:   OPEN
> Date:     6/22/2015
> Description: ----
>
> Description blah blah blah
> Thank you
"""
info =  get_info(search_string)

print info
print info["Type"]
print info["Status"]
print info["Date"]
print info["description"]
输出:

{'Status': 'OPEN', 'Date': '6/22/2015', 'Type': 'YUK', 'description': ' ----\n>\n> Description blah blah blah\n> \n'}
YUK
OPEN
6/22/2015
 ----
>
> Description blah blah blah
> 

我不认为这里使用的是
cvs
模块。如果只是进行简单的搜索,请使用字符串比较并按特征字符将其拆分。如果它更复杂,可以使用正则表达式

import os

with open("email.txt") as file:
    data = [line.replace("> ","") for line in file.readlines()]
    for line in data:
        s = line.split(":")
        if len(s) > 1:
            print s[1].strip()

我不认为这里使用的是
cvs
模块。如果只是进行简单的搜索,请使用字符串比较并按特征字符将其拆分。如果它更复杂,可以使用正则表达式

import os

with open("email.txt") as file:
    data = [line.replace("> ","") for line in file.readlines()]
    for line in data:
        s = line.split(":")
        if len(s) > 1:
            print s[1].strip()

您的文件是否为
csv
格式,可用于
csv
模块?您是否尝试使用csv解析器解析非csv文件(电子邮件)?那是行不通的;您需要编写自己的解析器。您的文件是否为
csv
格式,以便转到
csv
模块?您是否尝试使用csv解析器解析非csv文件(电子邮件)?那是行不通的;您需要编写自己的解析器。谢谢各位,似乎已经完成了。我将继续学习更多关于它的知识。真的很感谢你们的帮助。谢谢你们,似乎已经做到了。我将继续学习更多关于它的知识。非常感谢你的帮助。谢谢,我感谢你的帮助谢谢,我感谢你的帮助