正则表达式打印和无效响应

2024-05-16 09:42:09 发布

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

# Reading CSV
import csv
with open('A453_datafile_4_Mat 4 Data File.csv', 'r') as f:
    reader = csv.reader(f)
    for row in reader:
        print (row)

import re
email=input("What is your email")
password= input("What is your password")

with open('A453_datafile_4_Mat 4 Data File.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        print(row['email'])
        print(row['password'])

    pattern = (row['email'])    
    if re.match(pattern, email):
        print("Valid Email")
    else:
        print("Invalid Email")

    pattern= (row['password'])

    if re.match(pattern, password):
        print("Valid Password")
    else:
        print("Invalid Password")

输出

['email', 'password', 'firstname', 'secondname', 'street', 'city', 'pcode']
['', '', '', '', '', '', '']
['ojones@coldmail.net', 'ocrabc', 'Oliver', 'Jones', '53 Vale House', 'Portsmouth', 'P03 2TD']
['', '', '', '', '', '', '']
['asmith@ablealarms.net', 'alan123', 'Alan', 'Smith', '3 Porter Street', 'Cricklewood', 'HE3 4DH']
['', '', '', '', '', '', '']
['rakhter@bluebell.org', 'raj45', 'Raj', 'Akhter', '12 Middleport Road', 'Cheltenham', 'CH4 5GH']
['', '', '', '', '', '', '']
['hrdg4678@netwise.net', 'ha123', 'Jan', 'Pietersson', '56 Holde Street', 'Birmingham', 'B23 3RT']
['', '', '', '', '', '', '']
['miguel5@bluebell.net', 'happy3', 'Miguel', 'Santos', '45 Vine Avenue', 'Oxford', 'OX7 3RF']
What is your emailojones@coldmail.net
What is your passwordalan123


ojones@coldmail.net
ocrabc


asmith@ablealarms.net
alan123


rakhter@bluebell.org
raj45


hrdg4678@netwise.net
ha123


miguel5@bluebell.net
happy3

Invalid Email
Invalid Password

当我输入包含在我打印出来的csv文件中的数据时,我得到了无效的电子邮件和无效的密码语句,但是每当我输入最后一组数据时,它就表示数据是有效的。我不知道该怎么办,因为我还是python的初学者,我怀疑这与我定义2个模式有关。你知道吗


Tags: csvreyournetisemailpasswordwhat
1条回答
网友
1楼 · 发布于 2024-05-16 09:42:09

看起来像一个简单的缩进问题。 您需要缩进进行匹配和打印的所有行(从pattern = (row['email'])开始):

for row in reader:
    print(row['email'])
    print(row['password'])
    # BUG! only the above two statements get executed for every row
    # BUG: so the final value of email = row['email'] for the last row!

# BUG: so since the following lines are unindented, they only get executed once,
# which is not what you want!
pattern = (row['email']) ...  
if pattern == email: # or pattern.index(email) >= 0
# ...

相关问题 更多 >