gpt4 book ai didi

python - 从 Python 移植到 Ruby 时出现问题

转载 作者:行者123 更新时间:2023-12-01 05:44:32 24 4
gpt4 key购买 nike

我有一个简洁的 python 小脚本,我想将其移植到 Ruby,我认为它凸显了我对 Ruby 的不懂。我收到错误消息,指出存在意外的 END 语句,但我不明白为什么会这样。也许有一个关键字需要 END,或者我忘记了不需要 END 的关键字。以下是导致违规行的所有代码。违规行已被注释。

begin
require base64
require base32
rescue LoadError
puts "etext requires base32. use 'gem install --remote base32' and try again"
end

# Get a string from a text file from disk
filename = ARGV.first
textFile = File.open(filename)
text = textFile.read()

mailType = "text only" # set the default mailType

#cut the email up by sections
textList1 = text.split(/\n\n/)
header = textList1[0]

if header.match (/MIME-Version/)
mailType = "MIME"
end

#If mail has no attachments, parse as text-only. This is the class that does this
class TextOnlyMailParser

def initialize(textList)
a = 1
body = ""
header = textList[0]
@parsedEmail = Email.new(header)
while a < textList.count
body += ('\n' + textList[a] + '\n')
a += 1
end
@parsedEmail.body = body
end
end

def separate(text,boundary = nil)
# returns list of strings and lists containing all of the parts of the email
if !boundary #look in the email for "boundary= X"
text.scan(/(?<=boundary=).*/) do |bound|
textList = recursiveSplit(text,bound)
end
return textList
end
if boundary
textList = recursiveSplit(text,boundary)
end
end


def recursiveSplit(chunk,boundary)
if chunk.is_a? String
searchString = "--" + boundary
ar = cunk.split(searchString)
return ar
elsif chunk.is_a? Array
chunk do |bit|
recursiveSplit(bit,boundary);
end
end
end

class MIMEParser
def initialize(textList)
@textList = textList
@nestedItems = []
newItem = NestItem.new(self)
newItem.value = @textList[0]
newItem.contentType = "Header"
@nestedItems.push(newItem)
#setup parsed email
@parsedEmail = Email.new(newItem.value)
self._constructNest
end

def checkForContentSpecial(item)
match = item.value.match (/Content-Disposition: attachment/)
if match
filename = item.value.match (/(?<=filename=").+(?=")/)
encoding = item.value.match (/(?<=Content-Transfer-Encoding: ).+/)
data = item.value.match (/(?<=\n\n).*(?=(\n--)|(--))/m)
dataGroup = data.split(/\n/)
dataString = ''
i = 0
while i < dataGroup.count
dataString += dataGroup[i]
i ++
end #<-----THIS IS THE OFFENDING LINE
@parsedEmail.attachments.push(Attachment.new(filename,encoding,dataString))
end

最佳答案

您的问题是 i++ 行,Ruby 没有后置或前置递增/递减运算符,并且该行无法解析。我个人无法解释为什么 i++ 在 IRB 中求值,但 i++ 不执行任何操作。

而是用 += 1 替换您的 ++ 运算符,使最后一个 while :

while i < dataGroup.count
dataString += dataGroup[i]
i += 1
end

但也要考虑一下 ruby​​ 方式,如果您只是将其添加到字符串中,为什么不执行 dataString = dataGroup.join 而不是使用 while 构造进行循环?

关于python - 从 Python 移植到 Ruby 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16531263/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com