从两列中识别txt中的字符串

时间:2018-11-20 15:54:29

标签: python-3.x pandas dataframe

我希望我的程序读取txt中的行并使用两列来识别字符串,我尝试使用column1和column2中的row进行操作,但是它不起作用,我也不知道为什么,这是代码(这里我想在识别出字符串时打印出前5个字母,但稍后我会将这5个字母放入列表中。)

import pandas as pd
import re
import numpy as np

link = "excelfilett.txt"
file = open(link, "r")
frames_load = []
is_count_frames_load = False
for line in file:
    if "[Interface1]" in line:
        is_count_frames_load = True
    if is_count_frames_load== True:
        frames_load.append(line)
    if "[EthernetComNeed]" in line:
        break

number_of_rows_load = len(frames_load) -1
header_load = re.split(r'\t', frames_load[0])
number_of_columns_load = len(header_load)

frame_array_load = np.full((number_of_rows_load, number_of_columns_load), 0)
df_frame_array_load = pd.DataFrame(frame_array_load)
df_frame_array_load.columns= header_load

for row in range(number_of_rows_load):
    frame_row_load = re.split(r'\t', frames_load[row])
    for position in range(len(frame_row_load)):
        df_frame_array_load.iloc[row, position] = frame_row_load[position]
print(df_frame_array_load)
df_frame_array_load["[Name]"] = df_frame_array_load["[End1]"] + '\t' +  df_frame_array_load["[End2]"]
df_frame_array_load["[Name2]"] = df_frame_array_load["[End2]"] + '\t' +  df_frame_array_load["[End1]"]

print(df_frame_array_load["[Name]"])
print(df_frame_array_load["[Name2]"])

link = "excelfilett.txt"
file = open(link, "r")
frames_path = []
is_count_frames_path = False
for line in file:
    if "[Routing Paths]" in line:
        is_count_frames_path = True
    if is_count_frames_path== True:
        for row in df_frame_array_load["[Name]"] and df_frame_array_load["[Name2]"]:
            if row in line:
                print(row)
                print(line[0:4])
            if "[EthernetComNeed]" in line:
                break
    if "[EthernetComConfig]" in line:
        break

我想要作为输出的是在txt行中打印5个首字母。我使用的是它能识别字符串的情况,例如,当“ S1 \ tS2”在txt行中时,它将打印出我的前5个字母,因此“ FL_1”这两列包含的字符串为“ S1 \ tS2”和反数(如“ S2 \ tS1”),这是我遇到问题的那一点,它给了我

  

ValueError:系列的真值不明确。使用a.empty,a.bool(),a.item(),a.any()或a.all()。

在“ for column1 and column2:”行中。

1 个答案:

答案 0 :(得分:0)

我认为不可能一次读取两列中的行,我只是让我的程序分别读取两列,这就是我所做的更改:

link = "excelfilett.txt"
file = open(link, "r")
frames_path = []
is_count_frames_path = False
for line in file:
    if "[Routing Paths]" in line:
        is_count_frames_path = True
    if is_count_frames_path== True:
        for row in df_frame_array_load["[Name]"]:
            if row in line:
                print(row)
                print(line[0:4])
            if "[EthernetComNeed]" in line:
                break
        for row in df_frame_array_load["[Name2]"]:
            if row in line:
                print(row)
                print(line[0:4])
    if "[EthernetComConfig]" in line:
        break