Nested commands

81 Views Asked by At

One of the skills I am trying to learn is nested commands in Python as I am learning Python being a newbie. As such I have come up with this code. I am not sure what the mistake is. Here is the code:

file = open ("C:\\Users\\text.txt", "r")
print(file.read())

while True:
    content=file.readline()
    if not content:
        break
    return int(content.find(str(i)) for i in range (10))

The error I am getting is

SyntaxError: 'return' outside function

Despite the obvious, I cannot find where my error is. Some help please!

From reading each line of the file to return every number it finds on that line, whether that number is in between the word or standing alone.

1

There are 1 best solutions below

0
Ingwersen_erik On

Assuming that what you're trying to do is read a text file, iterate through each line of this file, find all numeric values that exist on each line and return those numbers that were found, you can consider using regex.

Option 1: finding both floats and integers

If you're trying to find both whole numbers (e.g., 1, 2, 3, ...) and fractions (e.g., 3.2, 5.15, 1.2345), you could write something like this:

import re


def find_numeric_values(text: str) -> list:
    """
    Find numeric values inside text.

    This function finds numeric values that exist inside a string
    and returns a list with the numbers that were found.

    The function can identify both floats and integer values, and
    can also find numbers placed between non-numeric values.

    The numbers that are found are converted into floats and integers,
    depending on whether they are whole numbers or not.

    Parameters
    ----------
    text : str
        The string to extract numeric values from.

    Returns
    -------
    List[str]
        A list with all the numbers found inside `text`,
        where each value is converted to either float or an integer,
        depending on whether it represents a whole number or not

    Examples
    --------
    """
    # Regular expression to match both integers and floating-point numbers
    pattern = r'(\b\d+\.?\d*\b|\d+)'
    
    # Find all matches in the text
    matches = re.findall(pattern, text)
    
    # List to store numeric values converted from string to either float or int
    numeric_values = []

    for match in matches:
        # Convert to float if '.' is in the match, else convert to int
        if '.' in match:
            numeric_values.append(float(match))
        else:
            numeric_values.append(int(match))
    
    # Return numeric values found in text
    return numeric_values


with open("C:\\Users\\text.txt", "r") as fh:
    # Reading lines from text file and returning a list where value
    # from this list is a single line from file.
    lines = lfh.readlines()

# Creating list to store the numeric values found
numeric_values = []

# going through each line of the text file
for line in lines:
    # Finding numeric values on a single line and adding them to 'numeric_values' list.
    numeric_values += find_numeric_values(line)

# Showing the numbers that were found inside the text file
print(numeric_values)

Example

Assuming your text file looks like this:

lorem ipsum 3.14, foo5bar another numb100er
B
C

D
e
100
45
s0me t3xt
m0re t22xt

The above solution would return the following list of numbers:

[3.14, 5, 100, 100, 45, 0, 3, 0, 22]

Option 2: Finding only whole numbers

If instead you're trying to find only whole numbers, replace the variable pattern defined inside the find_numeric_values function to this:

import re


def find_numeric_values(text: str) -> list:
    # Regular expression to match both integers and floating-point numbers
    pattern = r'(\d+)'
    # ... (rest of the code)

For the text file from the previous example, now the final output would be instead:

[3, 14, 5, 100, 100, 45, 0, 3, 0, 22]

Option 3: Finding single-digit numbers

If you're trying to extract from text numbers as single digit values, you could change the variable pattern to pattern = r'(\d)' (no + sign at the end).

Making this change would return the following list:

[3, 1, 4, 5, 1, 0, 0, 1, 0, 0, 4, 5, 0, 3, 0, 2, 2]

Notes

What's wrong with your original code

The error you're having occurs because you're trying to use a return statement outside a method or a function. To use a return statement you would need to move some of your code to a function and call it inside your while..loop. For example:

file = open("C:\\Users\\text.txt", "r")
print(file.read())

def text_find(content):
    return int(content.find(str(i)) for i in range (10))


while True:
    content=file.readline()
    if not content:
        break
    result = text_find(content) 

Bear in mind that the above code will only stop raising the exception you've mentioned in your question. It won't however achieve your desired output.

Use with statement when reading a text file

Instead of using file = open("C:\\Users\\text.txt", "r"), it's always a good idea to use the with statement for opening files.

The with statement ensures that resources are properly managed. When the block under the with statement is exited, the file is automatically closed, even if an exception is raised inside the block. This automatic management helps prevent file leaks, where files might remain open if an error occurs before the close() method is called.

In other words, instead of writing something like:

file = open("C:\\Users\\text.txt", "r")
print(file.read())
file.close()

You should consider writing it like this:

with open("C:\\Users\\text.txt", "r") as file:
    print(file.read())