Python Forum
Finding a number in a file printing out number and next word
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Finding a number in a file printing out number and next word
#1
Hi,
I am in Need of a little help. I wish to search within a text file and retrieve into another text file. The numbers and the words that appear after the numbers.
for example:
We have 40 white candies, 24 green ones, 12 red ones, 24 yellow ones and 20 blue ones.
40 white
24 green
12 red
24 yellow
20 blue
I managed to isolate the numbers - but I have confounded myself on how to grab the next word after the number.

# Import the regular expression module
import re

# Find the numeric values: matches
matches = re.findall('\d+', 'We have 40 white candies, 24 green ones, 12 red ones, 24 yellow ones and 20 blue ones.')

# Print the matches
print(matches)
RESULT
['40', '24', '12', '24', '20']
Reply
#2
Match the whitespace(\s) and word(\w+) after numbers
>>> import re
>>> 
>>> matches = re.findall(r'\d+\s\w+', 'We have 40 white candies, 24 green ones, 12 red ones, 24 yellow ones and 20 blue ones.')
>>> matches
['40 white', '24 green', '12 red', '24 yellow', '20 blue']
Reply
#3
Thank you - so appreciated
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Brick Number stored as text with openpyxl CAD79 2 455 Apr-17-2024, 10:17 AM
Last Post: CAD79
  [SOLVED] Pad strings to always get three-digit number? Winfried 2 365 Jan-27-2024, 05:23 PM
Last Post: Winfried
  Prime number detector Mark17 5 818 Nov-27-2023, 12:53 PM
Last Post: deanhystad
  Create X Number of Variables and Assign Data RockBlok 8 977 Nov-14-2023, 08:46 AM
Last Post: perfringo
  find the sum of a series of values that equal a number ancorte 1 508 Oct-30-2023, 05:41 AM
Last Post: Gribouillis
  Replace a text/word in docx file using Python Devan 4 3,474 Oct-17-2023, 06:03 PM
Last Post: Devan
  capturing multiline output for number of parameters jss 3 826 Sep-01-2023, 05:42 PM
Last Post: jss
  Sequential number for rows retrieved and storing the Primary UKey to the line number GYKR 2 584 Aug-22-2023, 10:14 AM
Last Post: GYKR
  doubling a number Skaperen 8 1,250 Jul-25-2023, 10:20 PM
Last Post: Skaperen
Question Extracting Version Number from a String britesc 2 1,104 May-31-2023, 10:20 AM
Last Post: britesc

Forum Jump:

User Panel Messages

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