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


Possibly Related Threads…
Thread Author Replies Views Last Post
  [split] University Assignment Help needed Nomathemba 4 3,814 Apr-20-2024, 12:24 PM
Last Post: jas31
Lightbulb Python University Laboratory - Help camibaldessini 3 1,353 Nov-03-2023, 01:28 PM
Last Post: Garrypyton
  reading text file and writing to an output file precedded by line numbers kannan 7 10,532 Dec-11-2018, 02:19 PM
Last Post: ichabod801
  University Assignment Help needed Diovanno 3 4,437 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