Python Forum
Searching a text file to find words matching a pattern
Thread Rating:
  • 1 Vote(s) - 4 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Searching a text file to find words matching a pattern
#1


Hello everyone,

First I'm a beginner at Python and I'm trying to learn by testing a few different thing and now I'm stuck. First of all I use this text file ss100.txt. It's in Swedish so there is of course åäö in the file and that's a problem as well. My question is as follows:
How do I find all words with a pattern like this: hxxxgxx where x is an unknown character?

I tried this but it's not working and I ran out of ideas:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import re

thefile = open("ss100.txt", "r")

for line in thefile:
    if re.match("h(.*)g(.*)(.*)", line) and len(line)==7:
        print line



A small example of the text file in the link above:
Quote:hopplös
hopplösa
hopplösare
hopplösares
hopplösas
hopplösast
hopplösaste
hopplösastes
hopplöse
hopplöses
hopplöshet
hopplösheten
hopplöshetens
hopplöshets
hopplöst


I'm looking for words with 7 characters starting with 'h' and a 'g' in position 5.
What is wrong with my code? Or is there a better way to do this.
Reply


Messages In This Thread
Searching a text file to find words matching a pattern - by Micael - Nov-07-2017, 06:37 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Matching string from a file tester_V 5 559 Mar-05-2024, 05:46 AM
Last Post: Danishhafeez
  find and group similar words with re? cartonics 4 833 Oct-27-2023, 05:36 PM
Last Post: deanhystad
  Form that puts diacritics on the words in the text Melcu54 13 1,689 Aug-22-2023, 07:07 AM
Last Post: Pedroski55
  FileNotFoundError: [WinError 2] The system cannot find the file specified NewBiee 2 1,692 Jul-31-2023, 11:42 AM
Last Post: deanhystad
  splitting file into multiple files by searching for string AlphaInc 2 1,003 Jul-01-2023, 10:35 PM
Last Post: Pedroski55
  Cannot find py credentials file standenman 5 1,742 Feb-25-2023, 08:30 PM
Last Post: Jeff900
  selenium can't find a file in my desk ? SouAmego22 0 783 Feb-14-2023, 03:21 PM
Last Post: SouAmego22
  Pypdf2 will not find text standenman 2 997 Feb-03-2023, 10:52 PM
Last Post: standenman
Thumbs Up Need to compare the Excel file name with a directory text file. veeran1991 1 1,194 Dec-15-2022, 04:32 PM
Last Post: Larz60+
  Find (each) element from a list in a file tester_V 3 1,315 Nov-15-2022, 08:40 PM
Last Post: tester_V

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020