【问题标题】:how to print all phone numbers in file [closed]如何打印文件中的所有电话号码[关闭]
【发布时间】:2020-08-19 21:00:42
【问题描述】:

此代码仅打印第一个电话号码。如何打印文件中的所有电话号码。

import re


def findn(filename):
    phonenum= re.compile(r'05\d\d\d\d\d\d\d\d')
    with open(filename) as f:
        for line in f:
            phone_number = re.search(phonenum, line)
            if phone_number:

                print("phone number found: "+phone_number.group())
            else:
                print('none')
        print('done')


findn("1.txt")

【问题讨论】:

  • 文件长什么样?每条线路是否有多个电话号码?
  • 只做功课
  • 把问题分解成小步骤,然后研究它们;互联网有大部分的答案。继续努力,继续挖掘。你会明白的。另外,正则表达式可以更简洁地表示为:05\d{8}

标签: python python-3.x


【解决方案1】:

要逐行打印文件,您只需使用 2 行 for 循环

file = open("name_of_file.txt", "r")

for line in file:
    print(line)

然后您可以将该行保存到一个变量中,以便稍后在循环中使用 -

file = open("name_of_file.txt", "r")

for line in file:
    phonenb = line

或者,您可以将每一行作为列表中的元素 -

file = "name_of_file.txt"
lines = [line.split() for line in open(file)]
print(lines)

【讨论】:

  • 好吧,这对我有用,但这里的问题是,如果我在同一行中有 2 个或更多电话号码,它只会打印第一个电话号码。我该如何解决??
  • @kkhh 您可以将每一行拆分为一个列表,然后使用每个列表上的 spit() 函数将每个列表拆分为每个单独的数字。然后使用 for 循环中的索引打印每个元素。
  • split() 不是spit()
【解决方案2】:

re.findall() 替换re.search() 可能会起作用(由于我没有1.txt,因此无法测试)。这是因为re.search() 只查找匹配的实例,而re.findall() 查找所有实例。

import re

def findn(filename):
    phonenum= re.compile(r'05\d\d\d\d\d\d\d\d')
    with open(filename) as f:
        for line in f:
            phone_number = re.findall(phonenum, line)
            if phone_number:
                print("phone number found: "+phone_number.group())
            else:
                print('none')
        print('done')


findn("1.txt")

【讨论】:

  • 我试过了,我有这个错误:" print("找到电话号码:"+phone_number.group()) AttributeError: 'list' object has no attribute 'group'"
  • 真的吗?什么错误?
  • print("找到电话号码:"+phone_number.group()) AttributeError: 'list' object has no attribute 'group'
猜你喜欢
  • 2020-01-04
  • 2019-05-02
  • 2022-06-18
  • 1970-01-01
  • 1970-01-01
  • 2020-10-16
  • 2013-08-20
  • 1970-01-01
  • 2012-07-26
相关资源
最近更新 更多