【问题标题】:searching for a string in a file using python faliure使用python失败在文件中搜索字符串
【发布时间】:2013-02-07 11:03:30
【问题描述】:

我正在使用此代码在特定文件中搜索电子邮件并将它们写入另一个文件。我使用了“in”运算符来确保电子邮件不重复。 但是这段代码在for line in f: 行之后不会被执行。 谁能指出我在这里犯的错误?

tempPath = input("Please Enter the Path of the File\n")
temp_file = open(tempPath, "r")
fileContent = temp_file.read()
temp_file.close()

pattern_normal = re.compile("[-a-zA-Z0-9._]+@[-a-zA-Z0-9_]+.[a-zA-Z0-9_.]+")

pattern_normal_list = pattern_normal.findall(str(fileContent))

with open('emails_file.txt', 'a+') as f:            
    for item in pattern_normal_list:            
        for line in f:
            if line in item:
                print("duplicate")
            else:
                print("%s" %item)
                f.write("%s" %item)
                f.write('\n')

【问题讨论】:

  • 问题是你第一次运行这个emails_file.txt 会是空的,所以没有行可以读,所以你永远不会有时间添加一个。 @Torxed 正在向您展示解决方案。

标签: python string file python-3.x


【解决方案1】:

新解决方案:

tempPath = input("Please Enter the Path of the File\n")
temp_file = open(tempPath, "r")
fileContent = temp_file.read()
temp_file.close()

pattern_normal = re.compile("[-a-zA-Z0-9._]+@[-a-zA-Z0-9_]+.[a-zA-Z0-9_.]+")

addresses = list(set(pattern_normal.findall(str(fileContent))))
with open('new_emails.txt', 'a+') as f:
    f.write('\n'.join(addresses))

我认为你的逻辑错误的,这行得通:

addresses = ['test@wham.com', 'heffa@wham.com']

with open('emails_file.txt', 'a+') as f:
    fdata = f.read()
    for mail in addresses:
        if not mail in fdata:
            f.write(mail + '\n')

无需过多阅读您的代码, 看起来您正在逐行循环,检查您还循环通过的地址是否存在于该行中,如果它不附加您的电子邮件?但是在 100 行中,有 99% 的地址不会在行中,因此您会得到不需要的添加。

我的代码 sn-p 的输出:

[Torxed@faparch ~]$ cat emails_file.txt 
test@wham.com
Torxed@whoever.com
[Torxed@faparch ~]$ python test.py 
[Torxed@faparch ~]$ cat emails_file.txt 
test@wham.com
Torxed@whoever.com
heffa@wham.com
[Torxed@faparch ~]$ 

【讨论】:

  • 我明白你的意思,我的逻辑是错误的。但是我改变了你说的仍然写重复的记录。我收到电子邮件的源文件包含重复的记录。这段代码将它们全部写入 emails.txt 文件。更改后的代码 sn-p: with open('emails_file.txt', 'a+') as f: fdata = f.read() for item in pattern_normal_list: if item not in fdata: print("%s" %item) f.write("%s" %item) f.write('\n')
  • 添加了一个更新版本,您可以在其中 1 读取包含重复电子邮件地址的文件。然后,过滤那个..等一下..呃..
【解决方案2】:
for line in f:

你不应该先调用 f.readlines() 吗?

lines = f.readlines()
for line in lines:

检查一下。

【讨论】:

  • 您不必使用with open() as f 语句,它本质上是展开为, f 是一个文件句柄,如果您遍历该文件句柄,您将一次得到一行根据 Python 中的默认实现。
  • @Torxed:但只有一次; OP 正在尝试遍历列表中每个项目的整个文件,如果没有 seek(),这将无法工作(尽管我同意这个答案可能更清楚)。
  • @Torxed:你不需要with 声明。使用f = open(filename) 打开文件并使用for line in f 进行读取可以正常工作。当然使用with 总是一个好主意。
  • 很公平,这不是必需的,但应该在描述的用法中:) 但是,你是对的,+1
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-07-26
  • 2012-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多