【问题标题】:Trying to combine the txt file and Regex试图结合txt文件和正则表达式
【发布时间】:2022-10-07 18:33:03
【问题描述】:

我想知道是否可以将正则表达式与.txt 文件结合起来。例如,我希望在打印文件时输出为 car.com。

Inside the .txt file

我试图在我的 Jupyter Notebook 中实现它来测试它

Abused = open(\"dictionaries/Abused.txt\", \'r\', encoding=\"utf-8\")
for line in Abused:
Abused_Result = re.search(r\"Car\", line)
print(Abused_Result.group())

但它导致 \'NoneType\' 对象没有属性 \'group\'。我仍在学习使用正则表达式,所以如果我错了,请纠正我。

谢谢!

  • 您的正则表达式搜索在该行中搜索“汽车”。由于您的文件不包含任何出现的“汽车”,它不会找到任何,因此是无。也许您可以进一步解释您要达到的目标。

标签: python regex jupyter-notebook


【解决方案1】:

您可以在例如测试您的 RegEx 字符串。 https://regex101.com/

您的当前将只匹配单词“Car”,因此文件中没有任何内容,导致re.searchNoneType 输出。

我不确定你想在这里使用 RegEx。我的理解是你想做:

Abused = open("dictionaries/Abused.txt", 'r', encoding="utf-8")
for line in Abused:
    print(f"car.{line}")

【讨论】:

    猜你喜欢
    • 2012-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多