gpt4 book ai didi

python - 使用 Python 匹配文件中的数字

转载 作者:太空宇宙 更新时间:2023-11-03 15:00:13 25 4
gpt4 key购买 nike

我有大约 15,000 个文件需要解析,这些文件可能包含我拥有的列表中的一个或多个字符串/数字。我需要用匹配的字符串分隔文件。

给定一个字符串:3423423987,它可能独立出现为“3423423987”,或“3423423987_1”或“3423423987_1a”、“3423423987-1a”,但也可能是“2133423423987”。但是,我只想检测不属于另一个数字的匹配序列,只有当它有某种后缀时。

所以 3423423987_1 是可以接受的,但 13423423987 不是。

我在使用正则表达式时遇到了麻烦,老实说我没怎么用过它。

简单地说,如果我用可能的正面和负面列表模拟这个,对于给定的列表,我应该得到 7 个命中。我想将文本提取到单词的末尾,以便稍后记录。

这是我的代码:

def check_text_for_string(text_to_parse, string_to_find):
import re
matches = []
pattern = r"%s_?[^0-9,a-z,A-Z]\W"%string_to_find
return re.findall(pattern, text_to_parse)

if __name__ =="__main__":
import re
word_to_match = "3423423987"
possible_word_list = [
"3423423987_1 the cake is a lie", #Match
"3423423987sdgg call me Ishmael", #Not a match
"3423423987 please sir, can I have some more?", #Match
"3423423987", #Match
"3423423987 ", #Match
"3423423987\t", #Match
"adsgsdzgxdzg adsgsdag\t3423423987\t", #Match
"1233423423987", #Not a match
"A3423423987", #Not a match
"3423423987-1a\t", #Match
"3423423987.0", #Not a match
"342342398743635645" #Not a match
]

print("%d words in sample list."%len(possible_word_list))
print("Only 7 should match.")
matches = check_text_for_string("\n".join(possible_word_list), word_to_match)
print("%d matched."%len(matches))
print(matches)

但显然,这是错误的。有人可以帮我吗?

最佳答案

您似乎只想确保数字不匹配为 float 的一部分。然后,您需要使用 lookarounds、lookbehind 和 lookahead 来禁止前后带有数字的点。

(?<!\d\.)(?:\b|_)3423423987(?:\b|_)(?!\.\d)

参见 regex demo

要同时匹配“前缀”(或者,最好在这里称它们为“后缀”),您需要添加类似 \S* 的内容(零个或多个非空格)或 (?:[_-]\w+)? (可选的 -_ 后跟 1+ 个单词字符)在模式的末尾。

详细信息:

  • (?<!\d\.) - 如果我们在当前位置之前有一个数字和一个点,则匹配失败
  • (?:\b|_) - 单词边界或 _ (我们需要它,因为 _ 是一个字符字符)
  • 3423423987 - 搜索字符串
  • (?:\b|_) ——同上
  • (?!\.\d) - 如果点 + 数字紧跟在当前位置之后,则匹配失败。

所以,使用

pattern = r"(?<!\d\.)(?:\b|_)%s(?:\b|_)(?!\.\d)"%string_to_find

参见 Python demo

如果可以有像Text with .3423423987 float value这样的 float ,您还需要添加另一个后视 (?<!\.)在第一个之后:(?<!\d\.)(?<!\.)(?:\b|_)3423423987(?:\b|_)(?!\.\d)

关于python - 使用 Python 匹配文件中的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38629459/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com