使用python 3.x从文本文件中查找匹配的关键字

时间:2015-01-26 11:48:29

标签: python python-3.x text

我有一个包含以下格式的文本文件和许多这样的行

Main keyword:Mainvariable, variable (1):name_1, variable (2, 3):name_2, variable(3, 1, 2):name_3, and so on....

我想在检查特定行中存在的Main关键字后检索,然后获取相应的信息。

例如,如果我在另一个文件的特定行中有变量(1)。我想以name_1

获得答案

输入文件

variable (1)
variable (3,1,2)
variable (1) as so on...

必需的输出:

name_1
name_3
name_1 and so on..
代码到现在为止:

print("\n-- ACCESSED VARIABLES --\n")
with open(commands_file, "r") as find_feature_access:
    with open("commands_analysis/feature_commands", "a") as feature_commands:
        with open("common_files/commands_library", "r") as feature_names:
            for line_1 in find_feature_access:
                current_line = line_1.strip()
                if current_line in possible_variables:
                    feature_commands.write(current_line + "\n")
                    for line_2 in feature_names:
                        if current_line in line_2:
                            line_part = line_2.strip(",")
                            if current_line in line_part:
                                required_part = line_part.strip(",")
                                print (required_part)

1 个答案:

答案 0 :(得分:0)

这样的东西?

sFILE = 'Main keyword:Mainvariable, variable (1):name_1, variable (2, 3):name_2, variable(3, 1, 2):name_3'

# I'm removing the beginning, but you could extract it if you want to check it
# ie "Main keyword:Mainvariable,"
sLINE = sFILE[26:]
# split the rest of the line at "variable"
sVARS = sLINE.split('variable')

for item in sVARS:
  # clean up whitespaces and commas
  item = item.strip(' ,')
  print('"',item,'"')

# prints "(1):name_1"
# prints "(2, 3):name_2"
# prints "(3, 1, 2):name_3"

现在你可以提取name_n或做一些其他必要的操作,或者在你的其他文件中做同样的事情并进行交叉检查?例如,填写列表中的名称(或根据您的需要决定),然后在另一个文件中提取“1”“2”和“3”并查找列表/字典?