Python Forum
Help with university work - reading and writing files
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help with university work - reading and writing files
#1
Hello,

Me and a lot of my classmates are so confused in today's work.

The answer sheet was published, but that didn't help us at all.

Here's what they want:

Write a Python function named extract_temp that is given a line read from a text file and displays the one number (integer) found in the string:
'The high today will be 15 degrees' → 15.

Here's my code (helped by the answer sheet):
# -----------------------------------------------------------------------------------------------------------------------
def extract_temp(s):
    for n in range(0,len(s)):
        if s[n].isdigit():
            ss = s[n:]
            for n1 in range(0,len(ss)):
                if not ss[n1].isdigit:
                    snum = s[n:n+1]
                    num=int(snum)
                    return num
# -----------------------------------------------------------------------------------------------------------------------

input_file = open('ExtractTemp.txt','r')

line = input_file.readline()

number = extract_temp(line)

print(line.strip(), "-", number)
The output:
Quote:The high today will be 15 degrees - None

Apparently, we just want the number "15" outputted, with None I think. I'm not quite sure.

Any help would be greatly appreciated.

Thank you!
Reply
#2
Here a hint,there is no need to complitcate the loop just loop over the string.
line = 'The high today will be 15 degrees'
temp = ''
for c in line:
    if c.isdigit():
        temp += c

print(int(temp)) 
Output:
15
Reply
#3
The shorter way would be to use regex.
Delete everything that is not a number,
hence you are left with a number, just 1 line.
Paul
It is more important to do the right thing, than to do the thing right.(P.Drucker)
Better is the enemy of good. (Montesquieu) = French version for 'kiss'.
Reply
#4
Why is your topic "reading and writing files" when that has almost nothing to do with the question? How about "Finding number in a string"?

Your idea is valid. The execution was flawed.
def extract_temp(s):
    for n in range(0, len(s)):
        if s[n].isdigit():
            ss = s[n:]
            for n1 in range(0, len(ss)):
                if not ss[n1].isdigit():
                    snum = ss[:n1]
                    num=int(snum)
                    return num

line = "The high today will be 15 degrees"
number = extract_temp(line)

print(line.strip(), "-", number)
Output:
The high today will be 15 degrees - 15
Your main problem was introducing ss. You either need to make ss and then only use n1 to index ss, or not use a substring and keep track of the start of the number string. In the example above I make the ss substring and then only used n1 when indexing ss. In the code below I don't make a substring and used a start index and an end index.
def extract_temp(s):
    for start in range(0, len(s)):
        if s[start].isdigit():  # Found start of the number string
            for end in range(start+1, len(s)):
                if not s[end].isdigit():  # Found end of the number string
                    return s[start:end]

line = "The high today will be 15 degrees"
number = extract_temp(line)

print(line.strip(), "-", number)
Notice that I didn't convert then number string to an int. If you aren't going to use it as a number, why convert?

Both the above examples fail if the input string is "The high today will be 15". With no characters trailing the number, the inner for loop exits before we encounter a non-digit character. So even though your original idea could be made to work, it doesn't work for some strings, and it is overly complicated.

There are many other ways to solve this problem. Snippsat's idea works great for strings that only contain only one number substring. Another way to solve the problem is split the string into words and test if any word is a number. You could use the regex library to search for a string of digits. That's what I would do. regex is fast and the code is very short.

One more thing. Notice that you can run my example without having to create a file named 'ExtractTemp.txt'. When posting code to the forum you should strive to do the same. Take a few minutes to clean out any unnecessary external references and make your code as short as it can be while still demonstrating the problem. And whenever possible post code that can be copied out of the forum and run without any changes. So include any required import statements. Make it easy for others to help you.
Reply
#5
2 examples. With and without regex and for both exception handling.

from collections.abc import Generator
import re

def extract_temp_re(line: str) -> int:
    """
    Return the first found decimal as int
    """
    if not line:
        raise ValueError("Got an empty str")

    try:
        return int(re.search(r"(\d+)", line)[1])
    except TypeError as e:
        raise ValueError("No decimal were found") from e


def extract_temp(line: str) -> int:
    """
    Return the first found decimal as int
    """
    if not line:
        raise ValueError("Got an empty str")
    
    def is_decimal_iter() -> Generator[tuple[int, bool], None, None]:
        for index, char in enumerate(line):
            yield index, char.isdecimal()

    start = None

    for index, is_decimal in is_decimal_iter():
        if is_decimal and start is None:
            start = index
        elif not is_decimal and start is not None:
            break

    if start is None:
        raise ValueError("No decimal were found")

    return int(line[start:index + 1])
 


examples = [
    "15 The high today will be degrees",
    "The 14 high today will be degrees",
    "The high today 15 will be degrees",
    "The high 15 today will be degrees",
    "The high today will be 15 degrees 42",
    "The high today will be 25 degrees",
    "",
    "aaaa",
]

for extract_function in (extract_temp_re, extract_temp):
    print(f"Testing function {extract_function.__name__}")
    for example in examples:
        try:
            print(example, "=>", extract_function(example))
        except ValueError as e:
            print("Error:", e)
    print()
Output:
Testing function extract_temp_re 15 The high today will be degrees => 15 The 14 high today will be degrees => 14 The high today 15 will be degrees => 15 The high 15 today will be degrees => 15 The high today will be 15 degrees 42 => 15 The high today will be 25 degrees => 25 Error: Got an empty str Error: No decimal were found Testing function extract_temp 15 The high today will be degrees => 15 The 14 high today will be degrees => 14 The high today 15 will be degrees => 15 The high 15 today will be degrees => 15 The high today will be 15 degrees 42 => 15 The high today will be 25 degrees => 25 Error: Got an empty str Error: No decimal were found
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#6
regex stuff

Learn re, it will always help you when searching strings!

import re

lines = """The high today will be -15.567 degrees.
The high today will be +15.567 degrees.
The high today will be -.567 degrees.
The high today will be -0.567 degrees.
The high today will be 15.567 degrees.
The high today will be 15 degrees."""

# explanation of '[+-]?(([0-9]+(\.[0-9]+)?)|(\.[0-9]+))'
# [+-]? maybe plus or minus before the number
# [0-9]+ one or more numbers
# need to escape . like this \. because . has meaning in re
# (\.[0-9]+)?) maybe decmal point followed by numbers
# | logical or in re
# (\.[0-9]+) maybe just a decimal point followed by numbers
# change \. for , if you use comma separated decimals

result = re.finditer('[+-]?(([0-9]+(\.[0-9]+)?)|(\.[0-9]+))', lines, re.MULTILINE)
for r in result:
    print(r.group())
Output:
+15.567 -.567 -0.567 15.567 15
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Lightbulb Python University Laboratory - Help camibaldessini 2 2,555 Sep-29-2023, 07:56 PM
Last Post: ICanIBB
  [split] University Assignment Help needed Nomathemba 2 5,860 Apr-07-2019, 11:49 PM
Last Post: micseydel
  reading text file and writing to an output file precedded by line numbers kannan 7 13,458 Dec-11-2018, 02:19 PM
Last Post: ichabod801
  University Assignment Help needed Diovanno 3 5,267 Apr-10-2018, 02:46 PM
Last Post: Diovanno

Forum Jump:

User Panel Messages

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