【发布时间】:2024-01-23 16:35:01
【问题描述】:
我正在处理大量文件(价值约 4gb),它们都包含 1 到 100 个具有以下格式的条目(两个 *** 之间是一个条目):
***
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:
***
现在我想以某种方式将这些导入 Pandas 进行质量分析,但显然我必须将其转换为 Pandas 可以处理的格式。所以我想编写一个脚本,将上面的内容转换为 .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 段的信息,但遗憾的是,一些文件在某些字段中包含几条白线。我基本上想做的是:
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 字符,这将大大减少错误条目的数量,但不会消除它们。
谁能指出我正确的方向?
提前致谢!
【问题讨论】:
-
用户来自哪里?
-
哦,我的错,用户是从文本文件名中提取的(所有的文本文件都是按用户 ID)。
-
也许只是尝试用“***”分割,然后用换行符分割结果?比将它们连接到一个字符串并将其打印到文本文件中。
标签: python regex data-analysis