Python—查找字符串中的所有数值,然后将每个数值唯一地存储在列表中

Python—查找字符串中的所有数值,然后将每个数值唯一地存储在列表中,python,regex,python-3.x,Python,Regex,Python 3.x,我想能够抓住任何和所有的数字值从字符串如果发现。然后将它们分别存储在列表中 phones = list() comment = "Sues phone numbers are P#3774794773 and P#6047947730." words = comment.split() for word in words: word = word.rstrip() nums = re.findall(r'\d{10,10}',word) if nums not in

我想能够抓住任何和所有的数字值从字符串如果发现。然后将它们分别存储在列表中

phones = list()
comment = "Sues phone numbers are P#3774794773 and P#6047947730."

words = comment.split()
for word in words:
    word = word.rstrip()

    nums = re.findall(r'\d{10,10}',word)
    if nums not in phones:
        phones.append(nums)

print(phones)
目前能够识别所有数值,但无法确定如何单独存储它们

phones = list()
comment = "Sues phone numbers are P#3774794773 and P#6047947730."

words = comment.split()
for word in words:
    word = word.rstrip()

    nums = re.findall(r'\d{10,10}',word)
    if nums not in phones:
        phones.append(nums)

print(phones)
我想将这两个值存储为。。。。3774794773,6047947730. 而不是列表中的列表

分别输出(打印)每个值的最终目标

当前打印:[[]、['3774794773']、['6047947730']]

需要打印:37747947736047947730


提前感谢。

将注释变量保存在文件中,然后使用此代码将它们分隔为变量

打开(“CS.txt”、“r”)作为f:
number1,number2=f.read().split(“”)
打印(编号1)

打印(数字2)
将注释变量保存在文件中,然后使用此代码将它们分隔为变量

打开(“CS.txt”、“r”)作为f:
number1,number2=f.read().split(“”)
打印(编号1)

print(number2)
您正在使用正则表达式执行双重任务(split基本上也是基于正则表达式的),只需使用与正则表达式匹配的10位数字即可完成整个任务,如下所示:

comment = "Sues phone numbers are P#3774794773 and P#6047947730."

nums = re.findall(r'\d{10,10}', comment)
print(nums)
如果希望数字也精确(不匹配更长的序列),可以执行以下操作:

comment = "Sues phone numbers are P#3774794773 123145125125215 and P#6047947730."

nums = re.findall(r'\b\d{10,10}\b', comment)
print(nums)
(\b是一个有趣的正则表达式符号,它并不真正匹配字符串的某一部分,而是匹配字符串中的“字符间距”)

两者都会导致:

['3774794773','6047947730']


您正在使用正则表达式执行双重任务(split基本上也是基于正则表达式的),只需使用与正则表达式匹配的10位数字即可完成整个任务,如下所示:

comment = "Sues phone numbers are P#3774794773 and P#6047947730."

nums = re.findall(r'\d{10,10}', comment)
print(nums)
如果希望数字也精确(不匹配更长的序列),可以执行以下操作:

comment = "Sues phone numbers are P#3774794773 123145125125215 and P#6047947730."

nums = re.findall(r'\b\d{10,10}\b', comment)
print(nums)
(\b是一个有趣的正则表达式符号,它并不真正匹配字符串的某一部分,而是匹配字符串中的“字符间距”)

两者都会导致:

['3774794773','6047947730']


...........
phones=re.findall(r'\d{10,10}',comment)
只需要长度为10的数字。有助于防止程序获取我不想要的值,例如“10”、“1000”等
re.findall(r'(?这确实有帮助,谢谢Wiktor,如果找到多个值,我如何单独存储它们?仍然会得到[[]、['3774794773'、['6047947730']].怎么回事,老兄?你为什么要拆分然后将它与一个数字进行匹配?….
phones=re.findall(r'\d{10,10}',comment)
只需要长度为10的数字。有助于防止程序获取我不想要的值,例如“10”、“1000”等
re.findall(r'(?谢谢你,Wiktor,如果发现不止一个,我如何分别存储它们?仍然会得到[[]、['3774794773']、['6047947730']]。见鬼,老兄?你为什么要拆分然后将其与数字匹配?这不是答案。错误的问题?这不是答案。错误的问题?