如何通过for循环在Python3中获得严格的单词匹配

时间:2018-09-24 09:32:25

标签: python python-3.x subprocess

我有一个以下代码段,我在其中搜索单词 koint ,但是它会打印所有与此相关的单词,例如kointkoint_localkoint_limited

除了正则表达式外,是否有严格的方法来查找这种类型的字符串/单词。

from subprocess import Popen, PIPE

CRED = '\033[91m'
CGRN = '\033[92m'
CEND = '\033[0m'

with open("kkdiff", "r") as lid:
    for line in lid:
        line = line.strip()
        proc = Popen(['id', line], stdout=PIPE,)
        myID = proc.communicate()[0].decode('utf-8')
        if 'koint' in myID:
            print(line, CGRN + "Success: " + CEND + "User exists in the Group")
        else:
            print(line, CRED + "Failed: " + CEND + "User does not exists in the Group")

当我只寻找koint时,上面的代码段返回下面:

user1 Failed: User does not exists in the Group
user30 Success: User exists in the Group (<-- koint_local)
user81 Success: User exists in the Group  (<-- koint_limited)
  

myID中的原始数据:

uid=24699(user1) gid=1001(skilla) groups=1786(koint),1614(koint_limited),101(torr)

在以上数据中,即使缺少kointkoint_limited也显示成功。

已返回:如果找到koint行,则打印成功。

正如我在文章开头提到的,除了正则表达式之外,还要澄清一下: 尽管正则表达式有效:

from subprocess import Popen, PIPE

CRED = '\033[91m'
CGRN = '\033[92m'
CEND = '\033[0m'

with open("kkdiff", "r") as lid:
    for line in lid:
        line = line.strip()
        proc = Popen(['id', line], stdout=PIPE,)
        myID = proc.communicate()[0].decode('utf-8')
        if re.search(r'\bkoint\b', myID):
            print(line, CGRN + "Success: " + CEND + "User exists in the Group")
        else:
            print(line, CRED + "Failed: " + CEND + "User does not exists in the Group")

2 个答案:

答案 0 :(得分:1)

正则表达式,将字符串与全字词 koint

匹配
>>> re.search(r'\bkoint\b', 'groups=1786(koint)') is not None
True
>>> re.search(r'\bkoint\b', '1614(koint_limited)') is not None
False

Regular Expression Syntax


看起来groups命令会更适合您的需求。

>>> proc = subprocess.Popen(['groups', line], stdout=PIPE)
>>> myID = proc.communicate()[0].decode('utf-8')
>>> 'koint' in myID.split()

答案 1 :(得分:0)

我已经编译了工作代码,因此它对于查看SO的人员可能很有用。现在有两种解决方案,有和没有create_table "profiles", force: :cascade do |t| t.string "name" t.bigint "user_id" ... t.index ["user_id"], name: "index_profiles_on_user_id" end create_table "users", force: :cascade do |t| t.string "email", default: "", null: false t.string "username", default: "", null: false ... end

1)没有regex

的解决方案
regex

2)基于from subprocess import Popen, PIPE, DEVNULL ##### color for success & Failed code ######## CRED = '\033[91m' CGRN = '\033[92m' CEND = '\033[0m' ############################################### with open(input("Please Enter the userfile: "), "r") as lid: for line in lid: line = line.strip() proc = Popen(['groups', line], stdout=PIPE, stderr=DEVNULL) myID = proc.communicate()[0].decode('utf-8') if 'koint' in myID.split(): print(line, CGRN + "Success: " + CEND + "user exists in the group") else: print(line, CRED + "Failed: " + CEND + "user doesn't exists in the group")

的解决方案
regex