我刚刚开始学习《代码2023的到来》,并试图用它来学习一些新的编程语言.我已经(有些)熟悉了Python,而且实际上我今天刚刚安装了Ruby.
第1天,第2部分,我使用正则表达式来搜索数字及其拼写版本.Python中的正则表达式(生成正确的结果):
(?=(0|1|2|3|4|5|6|7|8|9|zero|one|two|three|four|five|six|seven|eight|nine))
个
当我在Ruby中使用这个正则表达式时,我得到的结果为零.有趣的是,当我使用这个正则表达式时,我在python和ruby中得到了完全相同的结果,但这是不正确的答案:
r"0|1|2|3|4|5|6|7|8|9|zero|one|two|three|four|five|six|seven|eight|nine"
个
因此,我认为答案与积极的前瞻性断言有关,但我不知道为什么,以及它的做法有什么不同.
下面是这两个文件.
Python:
import re
input = open("../resources/input.txt","r")
lines = input.readlines()
targets = [
'0','1','2','3','4','5','6','7','8','9',
'zero','one','two','three','four','five','six','seven','eight','nine'
]
values = {
'0': 0,
'1': 1,
'2': 2,
'3': 3,
'4': 4,
'5': 5,
'6': 6,
'7': 7,
'8': 8,
'9': 9,
'zero': 0,
'one': 1,
'two': 2,
'three': 3,
'four': 4,
'five': 5,
'six': 6,
'seven': 7,
'eight': 8,
'nine': 9
}
sum = 0
for line in lines:
numbers = re.findall(r"(?=("+'|'.join(targets)+r"))", line)
firstDigitValue = values[numbers[0]] * 10
lastDigitValue = values[numbers[-1]]
sum += (firstDigitValue+lastDigitValue)
print(sum)
露比:
# Init vars
sum = 0
reg = /\d|zero|one|two|three|four|five|six|seven|eight|nine/
reg2 = /(?=(0|1|2|3|4|5|6|7|8|9|zero|one|two|three|four|five|six|seven|eight|nine))/
reg3 = /0|1|2|3|4|5|6|7|8|9|zero|one|two|three|four|five|six|seven|eight|nine/
values = {
'0' => 0,
'1' => 1,
'2' => 2,
'3' => 3,
'4' => 4,
'5' => 5,
'6' => 6,
'7' => 7,
'8' => 8,
'9' => 9,
'zero' => 0,
'one' => 1,
'two' => 2,
'three' => 3,
'four' => 4,
'five' => 5,
'six' => 6,
'seven' => 7,
'eight' => 8,
'nine' => 9
}
# Pipe the file line by line and do per line
File.foreach("../resources/input.txt", chomp: true) do |line|
# Get the first and last digits as their values
numbers = line.scan(reg3)
firstDigitValue = values[numbers[0]] * 10
lastDigitValue = values[numbers[-1]]
# accumulate
sum += (firstDigitValue+lastDigitValue)
end
puts sum