Home > front end >  Trying to combine the txt file and Regex
Trying to combine the txt file and Regex

Time:10-07

i want to know whether it's possible or not to combine regular expressions with a .txt file. for example, I want the output to be car.com when I print the file.

Inside the .txt file

I tried to implement it inside my Jupyter Notebook to test it out

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

But it resulted with 'NoneType' object has no attribute 'group'. i'm still learning on using Regex so please correct me if i'm wrong.

Thank you!

CodePudding user response:

You can test your RegEx string at e.g. https://regex101.com/

Your current RegEx string will only match the exact character sequence "Car" and hence nothing from the file, resulting in the NoneType output of re.search.

I'm not sure you want to use RegEx here. My understanding is that you want to do:

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

CodePudding user response:

There is no "car" in your text file so regex can't find it. For that you got the 'NoneType'

Tell me specifically what do you want?

If you want to print "car.com" if there is ".com" in the file then do this -

with open("dictionaries/Abused.txt", 'r', encoding="utf-8") as f:
    Abused = f.readlines()

for line in Abused:
    if "com" in line:
        print("car.com")

And if you want to know the line index the inside the if statement of the for loop add these two lines (Know that these two will remove the lines from the list not from the text)-

print(f"Line number: {Abused.index(line)}")
Abused.pop(Abused.index(line))
  • Related