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
  Control of the number of daemon error messages to the file MarPan 3 87 Mar-25-2026, 11:00 AM
Last Post: DeaD_EyE
  Exponential Number Conversion Tuurbo46 4 765 Jan-09-2026, 08:47 PM
Last Post: DeaD_EyE
  [split] print two different sequence number Reema 1 686 Nov-10-2025, 05:37 AM
Last Post: Gribouillis
  Send SMS from my phone number aster 4 4,789 May-11-2025, 05:48 PM
Last Post: TheTechNexus
  How to remove unwanted images and tables from a Word file using Python? rownong 2 2,306 Feb-04-2025, 08:30 AM
Last Post: Pedroski55
Question [redistribution] Reduce number + size of dependencies? Winfried 2 1,344 Jan-31-2025, 10:17 PM
Last Post: snippsat
  Syntax for Doubling a number ksp_802 3 1,466 Jan-12-2025, 07:04 PM
Last Post: ksp_802
  Printing the code line number arbiel 6 2,549 Jun-30-2024, 08:01 AM
Last Post: arbiel
  Finding the price based on industry and number of transactions chandramouliarun 1 2,213 Jun-04-2024, 06:57 PM
Last Post: marythodge4
Music Python Script Repeating Number When Saving Facebook Photos ThuanyPK 2 1,635 May-13-2024, 10:59 PM
Last Post: ebn852_pan

Forum Jump:

User Panel Messages

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