[英]Alternative for re.findall for python
我正在使用 arduino uno 和熱敏電阻來測量當前溫度。 我一直在使用 re.findall 來查找第 4 行中的匹配字符串,是否有替代方法而不是使用具有相同 function 的 re.findall? 因為我不允許在我的項目中使用 re。 謝謝
def my_function(port):
# Set COM Port.....
ser = serial.Serial(port, 9600, timeout=0,
parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, rtscts=0)
my_function('COM3')
# Set path to my Arduino device
# portPath = my_function
baud = 9600
sample_time = 1 # Takes temperature every 1 second
sim_time = 1 # Graphs 5 data points
# Initializing Lists
# Data Collection
data_log = []
line_data = []
# Establishing Serial Connection
connection = serial.Serial("com3", baud)
# Calculating the length of data to collect based on the
# sample time and simulation time (set by user)
max_length = sim_time / sample_time
# Collecting the data from the serial port
while True:
line = connection.readline()
line_data = re.findall('\d*\.\d*', str(line))
line_data = filter(None, line_data)
line_data = [float(x) for x in line_data]
line_data = [(x - 32) * 0.5556 for x in line_data] # list comprehension to convert line_data temp to celsius
line_data = [round(elem, 2) for elem in line_data] # round temp to 2 dp
if len(line_data) > 0:
print("The current temperature is:" + str(line_data[0]) + " celsius")
break
在這里查看這個答案: https://stackoverflow.com/a/4289557/7802476稍微修改一下也可以給出小數:
>>> txt = "h3110 23 cat 444.4 rabbit 11 2 dog"
>>> [float(s) for s in txt.split() if '.' in s and s.replace('.','').isdigit()]
>>> [444.4]
您的正則表達式\d*\.\d*
將匹配{.2, 2., 2.2,...}
等數字,但不會匹配{2}
,因為\.
必須在數字中。 上面也會做同樣的事情。
編輯:該解決方案不會像正則表達式那樣處理附加到字符串{2.2°C}
的數字。
為了讓它也處理單位,
[float(s.replace(f'{unit}', '')) for s in txt.split()
if '.' in s and s.replace('.','').replace(f'{unit}', '').isdigit()]
其中溫度unit
可以是'°C'
或'F'
。
但是,您的正則表達式匹配附加到任何字符串的所有浮點數。 也就是說, cat2.2rabbit
也會返回2.2
,不確定是否應該返回。
由於沒有給出樣本 output,下面是從文本中提取所有有效數字的代碼:
a = "Temperature = 54.3F 62.5, 79999 54.3°C 23.3C"
a+=' '
temp = []
i = 0
while i < len(a):
if (a[i].isdigit() or a[i] == '.'):
if a[i] == '.' and '.' in temp[-1]:
x = a.find(' ', i)
i = x
temp.pop()
elif i == 0:
temp[-1] += a[i]
elif len(temp)>0 and a[i-1] == temp[-1][-1]:
temp[-1] += a[i]
else:
temp.append(a[i])
i += 1
temp = list(map(float, temp)) # Float casting
print(temp)
Output:
['54.3', '62.5', '79999', '54.3', '23.3']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.