用python搜索文本文件中的精确变量

2024-04-19 04:40:21 发布

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

我试图搜索文件中的确切变量,但无法这样做。一、 e.如果我在文件中搜索“akash”,那么所有包含akash的行都会返回,即使它们只包含“akashdeph”而不包含确切的“akash”。你知道吗

__author__ = 'root'
def userinGroups(userName):
   with open('/etc/group','r') as data:
       associatedGroups=[]
       for line in data:
        if userName in line:
           associatedGroups.append(line.split(':')[0])
   return associatedGroups

print userinGroups('akash')

此函数只能返回包含“akash”的行,而不能返回包含“akashdeph”的行。 我尝试使用re模块,但找不到任何搜索变量的示例。 我也试过:

for 'akash' in line.split(':') 

但在这种情况下,如果一行包含多个组条目,则此操作失败。你知道吗


Tags: 文件infordatadefwithlineusername
2条回答

使用regex可以使用检索地址:

def userinGroups(userName):
    r = re.compile(r'\b{0}\b'.format(userName))
    with open('/etc/group', 'r') as data:
        return [line.split(":", 1)[0] for line in data if r.search(line)]

或使用子进程运行groups命令:

from subprocess import check_output
def userinGroups(userName):
    return check_output(["groups",userName]).split(":",1)[1].split()

大家好,我已经找到了解决我的问题的方法,所有成员的帮助下对此作出回应邮局。这里最终的解决方案

__author__ = 'root'
import re

def findgroup(line,userName):
    result=re.findall('\\b'+userName+'\\b',line)
    if len(result)>0:
        return True
    else:
        return False


def userinGroups(userName):
   with open('/etc/group','r') as data:
       associatedGroups=[]
       for line in data:
        if findgroup(line,userName):
           associatedGroups.append(line.split(':')[0])
   return associatedGroups



print userinGroups('akas')

相关问题 更多 >