PYTHON:在文本文档中搜索确切的字符串

时间:2017-01-07 01:51:50

标签: python database

我正在尝试在文本文件/数据库中搜索确切的用户名,但我的查询有多个输出

这是我的代码:

import re
txtFile = open("test.txt", "r")
userName = raw_input("USER: ")
for line in txtFile:
    if re.match(userName, line):
        print line

当我输入一般用户名时,例如" dragon"我得到了多个结果:

>>>
USER: dragon
dragon:46.245.173.123

dragonsAreCool:3.13.136.5

如何准确搜索而不是获得包含我的查询的多个结果?

1 个答案:

答案 0 :(得分:2)

       function GetUnassignedActiveRolesGrid(showOnlyDistrictRoles)
    {
        /* Unassigned Active Roles */
        unassignedActiveRolesGrid = $("#gridUnassignedActiveRoles").DataTable({
            fixedHeader: true,
            createdRow: function ( table  ) {
                setTabIndex(table);
            },
            processing: true,
            info: true,
            stateSave: false,
            ajax: {
                url: '@Url.Action("GetUnassignedActiveRoles", "UserAccount")',
                data: {accountId: @Model.UserNameDetails.AccountId, organizationId: '@Model.SelectedOrganizationId', showOnlyDistrictRoles: showOnlyDistrictRoles},
                dataSrc: "",
                type: "GET",
                dataType: "JSON"
            },
            paging: false,
            searching: true,
            autoWidth: false, // Disable the auto width calculation,
            language: {
                emptyTable: "Sorry, no role data available"
            },
            columns: [
                {data:  "ModuleName", title: "Module"},
                {data:  "Label", title: "Role"},
                {data:  "Description", title: "Description" },
                {title: "Navigation", className: "center"},
                {data:  "ModuleSortOrder", title: "ModuleSortOrder" },
                {data:  "RoleSortOrder", title: "RoleSortOrder" }
            ],
            order: [[4, "asc"], [5, "asc"], [0, "asc"], [1, "asc"]],
            columnDefs: [
                { width: "20%", targets: [0,1] },
                { width: "50%", targets: 2 },
                { width: "10%", targets: 3 },
                { orderable: false, targets: [2] },
                { orderable: false, targets: [3] },
                { targets: 3, data:
                    function(role) {
                        return role.OrganizationId == '@Model.SelectedOrganizationId' ? "<a class='link_UnassignedActive_Add' href='#anchorUnassignedActiveRoles'>Add</a>" : "";
                    }},
                { visible: false, searchable: false, targets: [4,5] }
            ]
        });
    }

或:

import re
userName = raw_input("USER: ")
with open("test.txt", "r") as txtFile:
    for line in txtFile:
        if re.match(userName + ':', line):
            print line
            break  # if you sure there is only one user, add break, make you code faster, else delete it.