如何读取文件并将某些数字从使用关键字复制到 excel 或另一个 txt 文件中?

How to read a file and copy certain numbers from the use of keywords into excel or another txt file?

我有一个文件,我目前只是手动将某些部分的数字传输到 excel,并希望将它们写入 txt 文件或直接写入 excel。

原始文件是一个sum文件(虽然本质上只是一个txt文件)

在文件的一部分,它有许多 CP,我想获得 v= 值和 G= 值。然后将它们排列在文件中的 txt file.For 示例中,它已打印到一半:

  import os
  from glob import glob

  list_of_files = glob('*.sum')  # get list of all .sum files

  for file in list_of_files:
      with open(file, 'r') as f: 
          content = f.read()

          # not sure how to find the keyword 'i.e. G=' and print what is 
          # behind 
          g = content        

          f = open("excelsheet.txt", "w+")   
          f.write(content)

您可以使用 csv and re 包来查找您需要的行。

如您所示读入一个文件。我正在使用以下 "text file"

测试我的 scipt
text = '''
CP# 1
V = -3.02132E+02
G = -5.15550E+12
K = -9.84693E+06
L =  1.16878E+06

CP# 2
V =  5.53209E+08
G =  6.06581E+08
K = -7.41506E+18
L = -9.87995E+02

CP# 3
V =  5.47807E+08
G = -5.03863E+00
K = -1.09701E+12
L = -5.30051E+09
'''

既然您已经加载了文件,请使用 re 包来查找您要查找的匹配项。您可以使用上面的 link 来了解有关语法的更多信息。

h_matches = re.findall(r'CP#\s\d', text)
v_matches = re.findall(r'(?<=V\s=)\s+[0-9+-E]+', text)
g_matches = re.findall(r'(?<=G\s=)\s+[0-9+-E]+', text)

headers  = [h for h in h_matches]
v_values = [m for m in v_matches]
g_values = [m for m in g_matches]

获得所有匹配项后,使用 csv 将数据写入 csv 文件。

with open('example.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    writer.writerow(['header', 'V', 'G'])

    for h, v, g in zip(headers, v_values, g_values):
        writer.writerow([h, v, g])

下面是example.csv

中的输出
header,V,G
CP# 1, -3.02132E+02, -5.15550E+12
CP# 2,  5.53209E+08,  6.06581E+08
CP# 3,  5.47807E+08, -5.03863E+00

如果您想写入现有的 excel sheet,您可以查看 xlsxwriter