嵌套命令
我正在学习Python,想掌握嵌套命令这项技能,因为我还是个新手。于是我写了这段代码,但不太确定哪里出错了。代码如下:
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))
我遇到的错误是:
SyntaxError: 'return' outside function
虽然错误信息很明显,但我还是找不到问题出在哪里。希望能得到一些帮助!
我想从文件的每一行读取内容,返回每个找到的数字,无论这个数字是夹在单词中间还是单独存在。
1 个回答
假设你想做的是读取一个文本文件,逐行查看这个文件,找到每一行中的所有数字,并返回这些找到的数字,你可以考虑使用正则表达式。
选项 1:查找浮点数和整数
如果你想找到整数(比如 1、2、3 等)和小数(比如 3.2、5.15、1.2345),你可以写类似这样的代码:
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)
示例
假设你的文本文件内容是这样的:
lorem ipsum 3.14, foo5bar another numb100er
B
C
D
e
100
45
s0me t3xt
m0re t22xt
上面的解决方案会返回以下数字列表:
[3.14, 5, 100, 100, 45, 0, 3, 0, 22]
选项 2:只查找整数
如果你只想找到整数,可以把在 find_numeric_values
函数中定义的 pattern
变量改成这样:
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)
对于之前示例中的文本文件,现在最终输出将会是:
[3, 14, 5, 100, 100, 45, 0, 3, 0, 22]
选项 3:查找单个数字
如果你想从文本中提取单个数字,可以把 pattern
变量改成 pattern = r'(\d)'
(末尾不要加 +
)。
这样修改后会返回以下数字列表:
[3, 1, 4, 5, 1, 0, 0, 1, 0, 0, 4, 5, 0, 3, 0, 2, 2]
注意事项
你原始代码的问题
你遇到的错误是因为你试图在一个 method
或 function
外部使用 return
语句。要使用 return
语句,你需要把一些代码放到一个函数里,并在 while..loop
中调用它。例如:
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)
请记住,上面的代码只会停止你在问题中提到的异常,但并不会达到你想要的输出。
读取文本文件时使用 with
语句
与其使用 file = open("C:\\Users\\text.txt", "r")
,不如使用 with
语句来打开文件,这样更好。
with
语句确保资源得到妥善管理。当退出 with
语句块时,文件会自动关闭,即使在块内发生了异常。这种自动管理有助于防止文件泄漏,即在调用 close()
方法之前,如果发生错误,文件可能会保持打开状态。
换句话说,不要写成这样:
file = open("C:\\Users\\text.txt", "r")
print(file.read())
file.close()
你应该考虑这样写:
with open("C:\\Users\\text.txt", "r") as file:
print(file.read())