如何在文件的每一行中搜索单词并在python中打印下一个值

2024-09-19 14:29:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我想搜索文件中的单词,并使用python以任何方式打印它的下一个值

代码如下:

def matchTest(testsuite, testList):

  hashfile = open("/auto/file.txt", 'a')

  with open (testsuite, 'r') as suite:
      for line in suite:
          remove_comment=line.split('#')[0]
          for test in testList:
              if re.search(test, remove_comment, re.IGNORECASE):
                  hashfile.writelines(remove_comment)
                  search_word=remove_comment.split(':component=>"', maxsplit=1)[-1].split(maxsplit=1)
                  print(search_word)
  hashfile.close()

remove_comment有以下几行:

{:component=>"Cloud Tier Mgmt", :script=>"b.py", :testname=>"c", --clients=$LOAD_CLIENT --log_level=DEBUG --config_file=a.yaml"}

{:skipfilesyscheck=>1, :component=>"Content Store", :script=>"b.py", --clients=$LOAD_CLIENT --log_level=DEBUG --config_file=a.yaml -s"}

{:script=>"b.py", :params=>"--ddrs=$DDRS --clients=$LOAD_CLIENT --log_level=DEBUG --config_file=a.yaml", :numddr=>1, :timeout=>10000, :component=>"Cloud-Connectivity" }

现在我希望输出仅为component值,如下所示:

Cloud Tier Mgmt

Content Store

Cloud-Connectivity

请任何人帮忙


Tags: pyclientlogcloudsearchcommentscriptload
3条回答

试试这个:

import re

remove_comment = '''{:component=>"Cloud Tier Mgmt", :script=>"b.py", :testname=>"c", --clients=$LOAD_CLIENT --log_level=DEBUG --config_file=a.yaml"}

{:skipfilesyscheck=>1, :component=>"Content Store", :script=>"b.py", --clients=$LOAD_CLIENT --log_level=DEBUG --config_file=a.yaml -s"}

{:script=>"b.py", :params=>"--ddrs=$DDRS --clients=$LOAD_CLIENT --log_level=DEBUG --config_file=a.yaml", :numddr=>1, :timeout=>10000, :component=>"Cloud-Connectivity" }'''

data = [x.split('"')[1] for x in re.findall(r'component=>[^,:}]*', remove_comment)]
print(data)

输出:

['Cloud Tier Mgmt', 'Content Store', 'Cloud-Connectivity']

试试这个功能

def get_component(file_path):
word_list = []
file = open(file_path, 'r')
i = 0;
for line in file:
    for word in line.split(','):
        word = word[1:]
        if word.startswith(":component=>"):
            word = word[13:-1]
            word_list.append(word)
            print(word)
            return word_list

您可以复制粘贴并给文件指定路径,这样它就可以正常工作

以下是我的输出:

['Cloud Tier Mgmt', 'Content Store', 'Cloud-Connectivity ']

假设代码的其余部分是正确的(我们看不到您使用的是什么正则表达式),您只需要将一行更改为:

search_word = remove_comment.split(':component=>"', maxsplit=1)[-1].split('"', maxsplit=1)[0]

相关问题 更多 >