将Ruby转换为Python

时间:2016-01-21 05:57:35

标签: python ruby regex

我正在尝试将我的ruby脚本转换为python。我对python不是很熟悉所以我得到了TypeError

printer.rb

Lease = Struct.new(:property, :renter)
lease_list = []

File.open('input.txt').readlines.each do |line|
  p, r = line.split(' - ')
  lease_list << Lease.new(p.tr('#', ''), r)
end

# sort by decimal value
lease_list.sort_by { |m| m.property.scan(/\d+/)[0].to_i }.each do |lease|
  puts "\##{lease.property} - #{lease.renter}"
end

printer.py

import re

class Lease:
  def __init__(self, renter=None, unit=None):
    self.renter = renter
    self.property = unit

lease_list = []
import sys
lines = open('input.txt', 'r')
for line in lines:
    l, m = line.split(' - ')
    lease_list.append(Lease(l,m))
lines.close()

print lease_list.sort(key=lambda lease: re.split(r"\d+", lease.property))

python错误

Traceback (most recent call last):   File "printer.py", line 16, in
<module>
    print lease_list.sort(key=lambda str: re.split(r"\d+", str))   File "printer.py", line 16, in <lambda>
    print lease_list.sort(key=lambda str: re.split(r"\d+", str))   File
"/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py",
line 171, in split
    return _compile(pattern, flags).split(string, maxsplit) TypeError: expected string or buffer

2 个答案:

答案 0 :(得分:3)

问题在于:

print lease_list.sort(key=lambda str: re.split(r"\d+", str))

str名称 [编辑:请参阅问题编辑历史记录] 您通常不应将其用作名称,即使是离婚)列表中包含的已分配值,因此传递给re.split() Lease 类型的对象:

lease_list.append(Lease(l,m))

这不是re.split的论据,它喜欢在str上咀嚼。因此 TypeError Lease有两个属性str之后的line.split(' - ')

self.renter = renter
self.property = unit

re.split()中使用其中一个(以您的用例为准):

print lease_list.sort(key=lambda obj: re.split(r"\d+", obj.renter))

或:

print lease_list.sort(key=lambda obj: re.split(r"\d+", obj.property))

忘记提及,使用listlist.sort进行排序将返回None,因为它会对列表进行排序,在此处打印值无效。

答案 1 :(得分:0)

如果您需要转换并且不想学习Python,那么我会推荐像www.varycode.com这样的在线转换器

但我建议学习python这是一门有很多不同优点的优秀语言!