在文本文件中组织分类数据并转换为CSV的最快方法 [英] Quickest way to organize categorized data in a text file and convert to CSV

查看:86
本文介绍了在文本文件中组织分类数据并转换为CSV的最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含数百行的文本文件.数据字段和值用冒号和一个空行分隔每个数据集.看起来像这样...

I have a text file with hundreds of rows. Data fields and values separated by a colon and one empty line separating each data set. It looks something like this...


icon:rain
temperatureHigh:55.37
temperatureLow:42.55
humidity:0.97
windSpeed:6.7
precipType:rain
precipProbability:0.97

icon:partly-cloudy-day
temperatureHigh:34.75
temperatureLow:27.1
humidity:0.8
windSpeed:15.32
precipType:snow
precipProbability:0.29

icon:clear-day
temperatureHigh:47
temperatureLow:31.72
humidity:0.64
windSpeed:9.27
precipType:rain
precipProbability:0.01

我正在努力将其格式化为具有所需输出的CSV格式...

I'm struggling trying to format this into a CSV with the desired output looking like this...


"icon","temperatureHigh","temperatureLow","humidity","windSpeed","precipType","precipProbability"
"rain","55.37","42.55","0.97","6.7","rain","0.97"
"partly-cloudy-day","34.75","27.1","0.8","15.32","snow","0.29"
"clear-day","47","31.72","0.64","9.27","rain","0.01"
...and so on, and so forth. 

我一直在尝试将Get-Content与replace一起使用,但是是否可以使用Import-CsvConvertTo-Csv?

I've been trying to use Get-Content with replace, but would it be possible to use Import-Csv or ConvertTo-Csv?

推荐答案

regex是解决方法:

$data = @'
icon:rain
temperatureHigh:55.37
temperatureLow:42.55
humidity:0.97
windSpeed:6.7
precipType:rain
precipProbability:0.97

icon:partly-cloudy-day
temperatureHigh:34.75
temperatureLow:27.1
humidity:0.8
windSpeed:15.32
precipType:snow
precipProbability:0.29

icon:clear-day
temperatureHigh:47
temperatureLow:31.72
humidity:0.64
windSpeed:9.27
precipType:rain
precipProbability:0.01

'@

$head = $data
$head = $head -replace '([^\s]+):([^\s]+)', '"$1",'
$head = $head -replace '\n\n', '::'
$head = $head -replace '\n', ''
$head = $head -replace '(.*?)::.*', '$1'
$head = $head -replace ',\s*$', ''
$head

$rows = $data
$rows = $rows -replace '([^\s]+):([^\s]+)', '"$2",'
$rows = $rows -replace '\n\n', '::'
$rows = $rows -replace '\n', ''
$rows = $rows + "::"
$rows = $rows -replace '::', "`n"
$rows = $rows -replace ',\s*\n', "`n"
$rows

输出:

"icon","temperatureHigh","temperatureLow","humidity","windSpeed","precipType","precipProbability"
"rain","55.37","42.55","0.97","6.7","rain","0.97"
"partly-cloudy-day","34.75","27.1","0.8","15.32","snow","0.29"
"clear-day","47","31.72","0.64","9.27","rain","0.01"

这篇关于在文本文件中组织分类数据并转换为CSV的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆