我正在处理大量文件(值大约4GB),它们都包含1到100个条目之间的任何地方,格式如下(两个***之间是一个条目):通过正则表达式和/或Python从文本文件中提取信息
***
Type:status
Origin: @z_rose yes
Text: yes
URL:
ID: 95482459084427264
Time: Mon Jul 25 08:16:06 CDT 2011
RetCount: 0
Favorite: false
MentionedEntities: 20776334
Hashtags:
***
***
Type:status
Origin: @aaronesilvers text
Text: text
URL:
ID: 95481610861953024
Time: Mon Jul 25 08:12:44 CDT 2011
RetCount: 0
Favorite: false
MentionedEntities: 2226621
Hashtags:
***
***
Type:status
Origin: @z_rose text
Text: text and stuff
URL:
ID: 95480980026040320
Time: Mon Jul 25 08:10:14 CDT 2011
RetCount: 0
Favorite: false
MentionedEntities: 20776334
Hashtags:
***
现在我想以某种方式将这些项目导入大熊猫进行质量分析,但很明显,我不得不将其转换成格式大熊猫可以处理。所以我想写的是,上述转换到.csv看起来像这样(用户是文件标题)的脚本:
User Type Origin Text URL ID Time RetCount Favorite MentionedEntities Hashtags
4012987 status @z_rose yes yes Null 95482459084427264 Mon Jul 25 08:16:06 CDT 2011 0 false 20776334 Null
4012987 status @aaronsilvers text text Null 95481610861953024 Mon Jul 25 08:12:44 CDT 2011 0 false 2226621 Null
(格式是不完美的,但希望你的想法)
我已经有一些代码工作的基础上,它经常在12的信息段,但不幸的是,一些文件包含一些领域的几个whitelines。什么我基本上希望做的是:
fields[] =['User', 'Type', 'Origin', 'Text', 'URL', 'ID', 'Time', 'RetCount', 'Favorite', 'MentionedEntities', 'Hashtags']
starPair = 0;
User = filename;
read(file)
#Determine if the current entry has ended
if(stringRead=="***"){
if(starPair == 0)
starPair++;
if(starPair == 1){
row=row++;
starPair = 0;
}
}
#if string read matches column field
if(stringRead == fields[])
while(strRead != fields[]) #until next field has been found
#extract all characters into correct column field
然而,问题出现某些字段可以包含的字段的字[] ..我可以检查一个\ n字符第一,这将大大减少量的错误条目,但不会消除它们。
任何人都可以指向正确的方向吗?
在此先感谢!
用户来自哪里? – depperm
哦,我的坏,用户从文本文件名称中提取(所有文本文件都是由用户ID)。 – user3394131
也许只是尝试按“***”拆分,然后用换行符拆分结果?将它们连接到一个字符串并将其打印到文本文件中。 – Eswemenasja