0

我是 python 新手,并试图创建一个脚本来修改 JS 文件的输出以匹配将数据发送到 API 所需的内容。JS 文件正在通过 urllib2 读取。

def getPage():
    url = "http://url:port/min_day.js"
    req = urllib2.Request(url)
    response = urllib2.urlopen(req)
    return response.read()

# JS Data
# m[mi++]="19.12.12 09:30:00|1964;2121;3440;293;60"
# m[mi++]="19.12.12 09:25:00|1911;2060;3277;293;59"

# Required format for API
# addbatchstatus.jsp?data=20121219,09:25,3277.0,1911,-1,-1,59.0,293.0;20121219,09:30,3440.0,1964,-1,-1,60.0,293.0

作为细分(必填值以粗体显示)

m[mi++]=" 19.12.12 09:30:00 | 1964 ;2121; 3440 ; 293 ; 60 "

并且需要将 -1,-1 的值添加到字符串中

我已经设法将日期转换为正确的格式并替换字符和换行符以使输出看起来像这样,但我有一种感觉,如果我需要能够重新排序这个字符串值,我就会走错路. 虽然看起来顺序在时间方面也是相反的。

20121219,09:30:00,1964,2121,3440,293,60;20121219,09:25:00,1911,2060,3277,293,59

任何帮助将不胜感激!我在想正则表达式可能是我需要的。

4

1 回答 1

2

这是一个正则表达式模式,用于去除您不想要的位

m\[mi\+\+\]="(?P<day>\d{2})\.(?P<month>\d{2})\.(?P<year>\d{2}) (?P<time>[\d:]{8})\|(?P<v1>\d+);(?P<v2>\d+);(?P<v3>\d+);(?P<v4>\d+);(?P<v5>\d+).+

并替换为

20\P<year>\P<month>\P<day>,\P<time>,\P<v3>,\P<v1>,-1,-1,\P<v5>,\P<v4>

此模式假定日期之前的字符是不变的。如果您想要更一般地处理该位,您可以替换m\[mi\+\+\]="为。[^\d]+

因此,要将其付诸实践,在 python 中:

import re

def getPage():
    url = "http://url:port/min_day.js"
    req = urllib2.Request(url)
    response = urllib2.urlopen(req)
    return response.read()    

def repl(match):
    return '20%s%s%s,%s,%s,%s,-1,-1,%s,%s'%(match.group('year'),
                                            match.group('month'),
                                            match.group('day'),
                                            match.group('time'),
                                            match.group('v3'),
                                            match.group('v1'),
                                            match.group('v5'),
                                            match.group('v4'))

pattern = re.compile(r'm\[mi\+\+\]="(?P<day>\d{2})\.(?P<month>\d{2})\.(?P<year>\d{2}) (?P<time>[\d:]{8})\|(?P<v1>\d+);(?P<v2>\d+);(?P<v3>\d+);(?P<v4>\d+);(?P<v5>\d+).+')

data = [re.sub(pattern, repl, line).split(',') for line in getPage().split('\n')]

# If you want to sort your data
data = sorted(data, key=lambda x:x[0], reverse=True)

# If you want to write your data back to a formatted string
new_string = ';'.join(','.join(x) for x in data)

# If you want to write it back to file
with open('new/file.txt', 'w') as f:
    f.write(new_string)

希望有帮助!

于 2012-12-19T01:50:02.053 回答