我有一个 Excel 文件,其中一列包含需求列表,还有一个存储表值的 JSON 文件。 Excel 文件中的要求包括对 JSON 文件中表格的引用,格式为“table x”,其中 x 是数字。并不是每个需求都有对应的表格。
例如,某个要求可能会规定:“立方体卫星的质量不得超出表 3 中的值。”要求中表格引用的格式始终为“table x”,其中 x 为任意数字。
这是 JSON 文件
{
"table 3": {
"footprint_cs_2u": "100x100 mm",
"height_cs_2u": "227 mm",
"feet_cs_2u": "8.5x8.5 mm",
"rails_edges_rounded_2u": "Rx1mm",
"footprint_cs_3u": "100x100 mm",
"height_cs_3u": "340.5 mm",
"feet_cs_3u": "8.5x8.5 mm",
"rails_edges_rounded_3u": "Rx1mm"
}
}
我设法做的是通过 .iloc[:,0] 命令读取并保存 1 个 Excel 列,以创建数据帧并读取 JSON 文件。
我看到您可能可以使用 RegEx 和 re.search() 命令来查找匹配项,但我无法弄清楚实现以及之后要做什么。 以这种方式:
import re
#Check if the string starts with "The" and ends with "Spain":
txt = "The rain in Spain"
x = re.search("^The.*Spain$", txt)
这是我的完整代码(如果有帮助的话)。
import pandas as pd
import numpy as np
import json
import re
import openpyxl
def translate_requirements(input_excel, tables_json, output_latex):
# read Excel-file
df = pd.read_excel(input_excel)
# read JSON file
with open(tables_json, 'r') as file:
tables = json.load(file)
# create dataframe for 1-collumn Excel content.
requirements = df.iloc[:, 0]
# Initialize translated requirements (empty array)
translated_requirements = []
# Output as LaTeX file | Here: example-doc
with open(output_latex, 'w') as latex:
latex.write(r"""
\documentclass{article}
.
.
.
"""
)
translate_requirements('input.xlsx', 'tables.json', 'output_latex.tex')
print('Data read')
到目前为止,我可以读取 Excel 和 JSON 文件。但是,我需要帮助将 JSON 文件中的表内容添加到使用该表的需求的相应 Excel 列中。
如何实现此映射,并随后将此信息包含在 LaTeX 文档中?
任何帮助或指示将不胜感激!
您可以在文字中搜索
table \d+
import re
text = 'The mass of the CubeSat shall not extend the values of table 3.'
results = re.findall('table \d+', text)
print(results)
结果:
['table 3']
稍后您可以检查列表是否不为空,然后使用第一个
results[0]
(或所有结果)在json中搜索
table = tables[results[0]]