为什么我的函数无法在给定字符串中找到 phone 数字?

Why is my function is not able to find a phone number in the given string?

我正在编写一些代码来查找 phone 数字(如果给定字符串中有的话)。这是代码:

def k(num):

 import sys
 def f():
   print('NO')
   sys.exit()


 if (num[0:2]).isdecimal() and (num[4:6]).isdecimal() and (num[8:11]).isdecimal():
   pass
 else:
   f()

 if num[3]=='-' and num[7]=='-' :
   print('The number that I found is' + ' ' + str(num))
 else:
     f()


inpt1=input('please enter the string.')
inpt2=inpt1.split()

for i in inpt2:
  if len(i)==12:
    k(i)
  else:
    pass

数字应采用 xxx-xxx-xxxx.

格式

然后我从维基百科上复制了一些文本“这些紧凑的结构引导 DNA 和其他蛋白质之间的相互作用,帮助控制 DNA 的哪些部分 transcribed.DNA 最初由 Friedrich Miescher 在1869. 它的分子结构首先由剑桥大学卡文迪许实验室的 James Watson 和 Francis 123-333-1111 Crick 确定”,并在中间某处插入了一个数字 (123-333-1111)文本,但程序只是返回 NO 而不是返回该数字。为什么会这样?

此外,如果我输入一些简单的输入,例如: My name is Harry Potter. My number is 222-333-1111 然后代码工作得很好!

编辑:可用的代码是:

def k(num):

 while True:
  if (num[0:2]).isdecimal() and (num[4:6]).isdecimal() and (num[8:11]).isdecimal():
    pass
  else:
    break


  if num[3]=='-' and num[7]=='-' :
    print('The number that I found is' + ' ' + str(num))
    break
  else:
     break

inpt1=input('please enter the string.')
inpt2=inpt1.split()

for i in inpt2:
  if len(i)==12:
    k(i)
  else:
    pass

您可以简单地使用re来轻松获得想要的结果。

>>> import re
>>> re.findall(r'\d{3}\-\d{3}\-\d{4}', 'My name is Harry Potter. My number is 222-333-1111')
['222-333-1111']
>>> tmp = 'These compact structures guide the interactions between DNA and other proteins, helping control which parts of the DNA are transcribed.DNA was first isolated by Friedrich Miescher in 1869. Its molecular structure was first identified by James Watson and Francis 123-333-1111 Crick at the Cavendish Laboratory within the University of Cambridge'
>>> re.findall(r'\d{3}\-\d{3}\-\d{4}', tmp)
['123-333-1111'] 

这个\d{3}\-\d{3}\-\d{4}部分基本上意味着我们需要找到一个以3位数字开头的模式,然后是-,然后是3位数字,然后是-,最后是另一个4位数。

我执行了你的代码运行,我发现问题是在输入的文本中,interactions这个词也是12个字符。所以最初进入函数的标准是满足的,但在函数内部它作为一个词不符合第一个标准并且它打印 NO 并且语句 sys.exit() 被执行因此其他词永远不会 checked.Hope 这有助于.