分割字符串以在分隔符之间查找单词?



给定如下一行:

jfdajfjlausername=Bob&djfkaak;jdskjpsasword=12345&

我想返回用户名和密码,在本例中是Bob12345

我尝试用&符号但是不知道如何找到单个单词,然后又尝试了下面的代码:

left='password='
right='&'
userleft='username='
for x in file.readlines():
if 'password=' and 'username=' in x:
text=str(x)
#password=(text[text.index(left)+len(left):text.index(right)])
#username=(text[text.index(userleft)+len(userleft):text.index(useright)])

不使用正则表达式,您可以拆分两次:一次在&上,一次在=上:

line = 'jfdajfjlausername=Bob&djfkaak;jdskjpsasword=12345&'
items = [item.split('=') for item in line.split('&')]

现在可以提取值了:

for item in items:
if len(item) == 2:
if item[0].endswith('password'):
password = item[1]
elif item[0].endswith('username'):
username = item[1]

如果你有一堆你正在寻找的键,比如('username', 'password'),你可以写一个嵌套循环来构建字典:

keys = ('username', 'password')
result = {}
for item in items:
if len(item) == 2:
for k in keys:
if item[0].endswith(k):
result[k] = item[1]
break

这使得它更容易检查你得到了所有你想要的值,例如if len(keys) == len(result): ...

如果您想要一个非常简单的方法,您可以这样做:

data = 'jfdajfjlausername=Bob&djfkaak;jdskjpassword=12345&'
#right of "username=" and left of "&"
un = data.split('username=')[1].split('&')[0]
#right of "password=" and left of "&"
pw = data.split('password=')[1].split('&')[0]
print(un, pw) #Bob, 12345

由于除了所需的键之外,过程是相同的,因此您可以执行如下操作并均匀化查询中获取任何键值的过程。这样做的一个有趣的副作用是:即使您的示例查询没有以"&;&&;"结尾,这仍然可以工作。这是因为剩下的所有内容都将在.split('&')[0]的结果中,并且根本不会有.split('&')[1]。下面没有使用.split('&')[1],所以没有关系。

query = 'jfdajfjlausername=Bob&djfkaak;jdskjpassword=12345&'
key2val = lambda q,k: q.split(f'{k}=')[1].split('&')[0]
un = key2val(query, 'username')
pw = key2val(query, 'password')
print(un, pw) #Bob, 12345

此方法可能优于regex。它一定会更快,它不需要任何依赖关系或循环,而且它足够灵活,允许您从任何键中获取值,无论顺序如何,都不需要更改任何内容。

使用正则表达式:

import re
for x in file.readlines():
if 'password=' in x and 'username=' in x:
text=str(x)
username = re.findall('username=(w+)',text)
password = re.findall('password=(w+)',text)

注意更新后的if语句。在原始代码中,if检查"password="是否计算为True,它总是会这样做——因为它不是一个空字符串。

您可以使用一个正则表达式来解析这些信息:

import re
s = "jfdajfjlausername=Bob&djfkaak;jdskjpassword=12345&"
regex = "username=(?P<username>.+)&.*password=(?P<password>.+)&"
match = re.search(regex, s)
print(match.groupdict())
{'username': 'Bob', 'password': '12345'}

在循环文件中的行时实现此功能将看起来像:

regex = "username=(?P<username>.+)&.*password=(?P<password>.+)&"
with open('text') as f:
for line in f:

match = re.search(regex, line)
if match is not None:
print(match.groupdict())

更新#2

读取一个名为"text"并解析出每一行的用户名和密码,如果它们都存在的话。

此解决方案假设用户名和密码字段都以"&&quot;结尾。

更新# 3:

请注意,即使用户名和密码的顺序颠倒,这段代码也可以工作。

import re
with open('text') as f:
for line in f:
print(line.strip())
# Note that ([^&]+) captures any characters up to the next &.
m1 = re.search('username=([^&]+)', line)
m2 = re.search('password=([^&]+)', line)
if m1 and m2:
print('username=', m1[1])
print('password=', m2[1])

输出:

jfdajfjlausername=Bob&djfkaak;jdskjpassword=12345&
username= Bob
password= 12345

最新更新