我遇到了一个挑战,我试图使用 split.strings 来解决,但这似乎不是为我需要的不可变字符串设计的,而是主要用于空格和单个字符的删除。我也尝试过正则表达式,但由于它们在我当前的 python 类(class)中还有几周时间才到期,所以我对它们的工作方式有点困惑(尽管我知道它们的基本用途)。
因此,我有一个 JSON 文件,其中显示来自工厂的机器和人员数据,我需要将机器数据与在设施内收集的人员数据分开进行解析。转换 JSON 文件并选择所需的数据正在工作,但在一个名为 name
的参数中是我需要分离出来的人员和机器信息的混合体。两个分支的示例如下:
"id": "b4994c877c9c",
"name": "forklift_0001", # here is the machine
"areaId": "Tracking001",
"areaName": "Ajoneuvo",
"color": "#FF0000",
"coordinateSystemId": "CoordSys001",
"coordinateSystemName": null,
"covarianceMatrix": [
"id": "b4994c879275",
"name": "guest_0001", # here is a person
"areaId": "Tracking001_2D",
"areaName": "staff1",
"color": "#CCFF66",
"coordinateSystemId": "CoordSys001",
"coordinateSystemName": null,
"covarianceMatrix": [
我必须转换的代码如下:
for f in file_list:
print('Input file: ' + f) # Replace with desired operations
with open(f, 'r') as f:
distros = json.load(f)
output_file = 'Output' + str(output_nr) + '.csv'
with open(output_file, 'w') as text_file:
for distro in distros:
print(distro['name'] + ',' + str(distro['positionTS']) + ',' + str(distro['position']), file=text_file)
所以我需要在 distro['name']
数组(它是一个数组吗?)中做的是遍历 500k 行并要求它删除任何不存在的内容叉车、起重机、机器等,只留下它们(后来又相反),这是我无法弄清楚的。
衷心感谢所有帮助。
最佳答案
据我了解您的问题,您希望根据“名称”标签为每个条目指定一个“机器”或“人”标志。
分配这样的标志(或者直接写入适当的文件)可以通过例如类似的事情来完成
with open(file1, 'w') as _file1, open(file2, 'w') as _file2, open(file3, 'w') as _file3:
for distro in distros:
yourstring = distro['name'] + ',' + str(distro['positionTS']) + ',' + str(distro['position'])
if distro['name'].startswith(('forklift','crane',...)):
_file1.write(yourstring)
elif distro['name'].startswith(('guest','employee',...)):
_file2.write(yourstring)
else:
_file3.write(yourstring)
打开并一起写入的三个文件最终将包含所有条目,在机器、人员或两者之间分开。
这能解决您的问题吗?
关于python - 从字符串中删除多个字符(形成一个单词),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50681795/