ruby 读取文本_使用Ruby进行文本处理

ruby 读取文本

在与Perl或Python相同的页面上,Ruby具有强大的功能,可以成为强大的文本处理语言。 本文简要地讨论了Ruby的文本数据处理能力,以及如何使用它来有效处理文本数据的不同格式,无论是CSV数据还是XML数据。

Ruby弦

Ruby中的字符串是保存,比较和操作文本数据的强大方法。 在Ruby中,String是一个类,您可以通过调用String::new或仅分配一个文字值来实例化。

在为字符串分配值时,可以使用一对单引号(')将该值括起来,也可以使用一对双引号(“”)。 单引号和双引号在某些方面以不同的方式指定了字符串。 双引号允许转义序列使用前导反斜杠(\),还允许使用#{}运算符对字符串中的表达式求值。 单引号字符串是简单,直接的文字。

清单1是一个示例。

清单1.使用Ruby字符串:定义字符串
message = 'Heal the World…'

puts message

message1 = "Take home Rs #{100*3/2} "

puts message1

Output :

# ./string1.rb

# Heal the World…

# Take home Rs 150

在这里,第一个字符串用一对单引号定义。 第二个使用一对双引号。 在第二个示例中, #{}的表达式在显示之前求值。

定义字符串的另一种有用方法通常用于多行字符串定义。

从这里开始,我将使用交互式Ruby控制台irb >>进行解释。 您应该在安装Ruby的同时安装它。 如果没有,我建议您获得irb Ruby gem并安装它。 这是了解Ruby及其模块的非常有用的工具。 安装后,可以使用irb >>命令运行它。

清单2.使用Ruby字符串:定义多行字符串
irb>> str = >>EOF

irb>> "hello world

irb>> "how do you feel?

irb>> "how r u ?

irb>> EOF

"hello, world\nhow do you feel?\nhow r u?\n"

irb>> puts str

hello, world
how do you feel?
how r u?

清单2中>>EOFEOF之间的所有内容都被视为字符串的一部分,包括\n (换行)字符。

Ruby String类具有一组强大的方法来处理和处理存储在其中的数据。 在清单中的示例34 ,和5示出了其中的几个。

清单3.使用Ruby字符串:串联
irb>> str = "The world for a horse"    # String initialized with a value

The world for a horse

irb>> str*2                     # Multiplying with an integer returns a 
                                         # new string containing that many times
                                         # of the old string.

The world for a horseThe world for a horse

irb>> str + " Who said it ? "      # Concatenation of strings using the '+' operator

The world for a horse Who said it ?

irb>> str<<" is it? "	  # Concatenation using the '<<' operator

The world for a horse is it?

提取子字符串并处理字符串的各个部分

清单4.使用Ruby字符串:提取和操作
irb>> str[0]	# The '[]' operator can be used to extract substrings, just 
                        # like accessing entries in an array.
                        # The index starts from 0.
84			# A single index returns the ascii value
                        # of the character at that position

irb>> str[0,5]	# a range can be specified as a pair. The first is the starting 
                        # index , second is the length of the substring from the
                        # starting index.

The w

irb>> str[16,5]="Ferrari"   # The same '[]' operator can be used
                                  # to replace substrings in a string
                                  # by using the assignment like '[]='
irb>>str

The world for a Ferrari

Irb>> str[10..22]		# The range can also be specified using [x1..x2] 

for a Ferrari

irb>> str[" Ferrari"]=" horse"	# A substring can be specified to be replaced by a new
                               # string. Ruby strings are intelligent enough to adjust the
                               # size of the string to make up for the replacement string.

irb>> s

The world for a horse

irb>> s.split	       # Split, splits the string based on the given delimiter
                               # default is a whitespace, returning an array of strings.

["The", "world", "for", "a", "horse"]

irb>> s.each(' ') { |str| p str.chomp(' ') }

                               # each , is a way of block processing the
			       # string splitting it on a record separator
			       # Here, I use chomp() to cut off the trailing space

"The"
"world"
"for"
"a"
"horse"

Ruby String类还提供许多其他实用程序方法,包括更改大小写,获取长度,删除记录分隔符,扫描字符串,加密,解密字符串的方法,等等。 另一种有用的方法是freeze方法,通过该方法可以使字符串不可变。 在String str上调用该方法之后( str.freeze ,无法修改str )。

Ruby也有所谓的析构方法。 以感叹号(!)结尾的方法将永久修改字符串。 普通方法(末尾没有感叹号的方法)会修改并返回调用它们的字符串的副本。 感叹号方法会修改调用该方法的字符串。

清单5.使用Ruby字符串:永久性修改字符串
irb>> str = "hello, world"

hello, world

irb>> str.upcase

HELLO, WORLD

irb>>str		       # str, remains as is.

Hello, world

irb>> str.upcase!	       # here, str gets modified by the '!' at the end of 
                               # upcase.
HELLO, WORLD

irb>> str

HELLO, WORLD

清单5中str的字符串被upcase!修改了upcase! 方法,但是只有upcase方法返回大小写已更改的字符串的副本。 这些! 方法有时非常有用。

Ruby Strings非常强大。 一旦将数据捕获为字符串,就可以使用多种方法以一种非常简单有效的方式来处理它们。

处理CSV文件

CSV文件是表示表格数据的一种非常常见的方式,最常用作从电子表格导出的数据的格式(例如具有联系人详细信息的联系人列表)。

Ruby具有强大的库来处理和处理此类文件。 csv是处理CSV文件的ruby模块。 它具有创建,读取和解析此类文件的方法。

清单6中的示例显示了如何创建这样的CSV文件,然后使用Ruby csv模块对其进行解析。

清单6.处理CSV文件:创建和解析CSV文件
require 'csv'

writer = CSV.open('mycsvfile.csv','w')

begin

	print "Enter Contact Name: "

	name = STDIN.gets.chomp

	print "Enter Contact No: "

	num = STDIN.gets.chomp

	s = name+" "+num

	row1 = s.split

	writer << row1

	print "Do you want to add more ? (y/n): "

	ans = STDIN.gets.chomp

end while ans != "n"

writer.close

file = File.new('mycsvfile.csv')

lines = file.readlines

parsed = CSV.parse(lines.to_s)

p parsed

puts ""

puts "Details of Contacts stored are as follows..."

puts ""

puts "-------------------------------"

puts "Contact Name | Contact No"

puts "-------------------------------"

puts ""

CSV.open('mycsvfile.csv','r') do |row|

	puts row[0] + " | " + row[1]	

	puts ""
end

清单7显示了输出:

清单7.处理CSV文件:创建和解析CSV文件输出
Enter Contact Name: Santhosh

Enter Contact No: 989898

Do you want to add more ? (y/n): y

Enter Contact Name: Sandy

Enter Contact No: 98988

Do you want to add more ? (y/n): n

Details of Contacts stored are as follows...

---------------------------------
Contact Name | Contact No
---------------------------------

Santhosh | 989898

Sandy | 98988

让我们快速回顾一下示例。

首先,包含csv模块( require 'csv' )。

要创建名为mycsvfile.csv的新CSV文件,请使用CSV.open()调用将其打开。 这将返回一个writer对象。

本示例创建一个CSV文件,其中包含一个简单的联系人列表,其中存储了该人的姓名及其电话号码。 在循环中,要求用户输入联系人的姓名和电话号码。 名称和电话号码连接成一个字符串,然后分成两个字符串组成的数组。 该数组传递到writer对象,以写入CSV文件。 因此,一对CSV值作为一行存储在文件中。

一旦脱离循环,一切就完成了。 现在关闭编写器并保存文件中的数据。

下一步是解析创建的CSV文件。

打开和解析文件的一种方法是创建一个使用新CSV文件名称的新File对象。

调用readlines方法将文件中的所有行读入一个名为lines的数组中。

通过调用lines.to_slines数组转换为String对象,并将该字符串传递给CSV.parse方法,该方法解析CSV数据并以数组形式和数组形式返回内容。

接下来,您将看到另一种打开和解析文件的方法。 在读取模式下使用CSV.open调用再次打开文件。 这将返回一个行数组。 以某种格式打印每一行以显示联系人详细信息。 这里的每一行都是文件中的一行。

如您所见,Ruby提供了一个用于处理CSV文件和数据的功能强大的模块。

处理XML文件

为了使用XML文件,Ruby拥有一个强大的内置库,称为REXML。 这可用于读取和解析XML文档。

查看此XML文件,并尝试使用Ruby和REXML对其进行解析。

以下是一个简单的XML文件,列出了在线购物中心中典型购物车的内容。 它具有以下元素:

  • cart –是根元素
  • user -购物的用户
  • item用户已添加到购物车中的项目
  • id, pricequantity -项目的子元素。

清单8显示了XML的结构:

清单8.使用XML文件:样本XML文件
<cart id="userid">

<item code="item-id">

	<price>

		<price/unit>

	</price>

	<qty>

		<number-of-units>

	</qty>

</item>

</cart>

转到下载以获取示例XML文件。 现在,加载此XML文件并使用REXML在树中进行解析。

清单9.使用XML文件:解析XML文件
require 'rexml/document'

include REXML

file = File.new('shoppingcart.xml')

doc = Document.new(file)

root = doc.root

puts ""

puts "Hello, #{root.attributes['id']}, Find below the bill generated for your purchase..."

puts ""

sumtotal = 0

puts "-----------------------------------------------------------------------"

puts "Item\t\tQuantity\t\tPrice/unit\t\tTotal"

puts "-----------------------------------------------------------------------"

root.each_element('//item') { |item| 

code = item.attributes['code']

qty = item.elements["qty"].text.split(' ')

price = item.elements["price"].text.split(' ')

total = item.elements["price"].text.to_i * item.elements["qty"].text.to_i

puts "#{code}\t\t  #{qty}\t\t          #{price}\t\t         #{total}"

puts ""

sumtotal += total

}

puts "-----------------------------------------------------------------------"

puts "\t\t\t\t\t\t     Sum total : " + sumtotal.to_s

puts "-----------------------------------------------------------------------"

清单10显示了输出。

清单10.使用XML文件:解析XML文件输出
Hello, santhosh, Find below the bill generated for your purchase...

-------------------------------------------------------------------------
Item            Quantity                Price/unit              Total
-------------------------------------------------------------------------
CS001             2                          100                      200

CS002             5                          200                     1000

CS003             3                          500                     1500

CS004             5                          150                      750

-------------------------------------------------------------------------
                                                         Sum total : 3450
--------------------------------------------------------------------------

清单9中的示例解析了购物车XML文件,并生成了一个账单,其中包含单个商品的总和以及购买的总和( 清单10 )。

让我们快速浏览一下。

首先,包括Ruby的REXML模块。 它具有解析XML文件的方法。

打开shoppingcart.xml文件,并从中创建一个Document对象。 该Document对象是包含已解析的XML文件的对象。

将文档的根目录分配给元素对象root 。 现在,这将指向XML中的cart标签。

每个元素对象都有一个属性对象,该对象是元素属性名称作为键,其值作为值的哈希。 在这里, root.attributes['id']将给出root元素的属性id的值,在这种情况下,该值是userid

接下来,将汇总初始化为0并打印标题。

每个元素对象还具有一个称为elements的对象, each对象和[]方法用于访问子元素。 该块遍历具有名称itemroot元素的所有子元素,该名称由XPath表达式//item指定。 每个元素对象还具有一个属性text ,其中包含该元素的文本值。

接下来,获取item元素的code属性以及priceqty元素的文本值,并计算该项目的总计。 将详细信息打印到帐单中。 另外,将项目总计添加到汇总中。

最后,打印总计。

此示例说明使用REXML和Ruby解析XML文件是多么容易和简单。 动态生成XML文件以及添加和删除元素及其属性非常容易。

清单11.使用XML文件:生成XML文件
doc = Document.new

doc.add_element("cart1", {"id" => "user2"})

cart = doc.root.elements[1]

item = Element.new("item")

item.add_element("price")

item.elements["price"].text = "100"

item.add_element("qty")

item.elements["qty"].text = "4"

cart .elements << item

清单11中的代码段通过创建一个cart元素,一个item元素及其子元素来创建XML结构。 它用值填充它们,并将它们添加到Document根目录。

同样,要删除元素和属性,请使用Elements对象的delete_elementdelete_attribute方法。

上面是所谓的树解析的示例。 解析XML文档的另一种方法称为流解析 。 这比树解析要快,并且可以在需要速度的地方使用。 流解析是基于事件的,并且可以与侦听器一起使用。 遇到标签时,将调用侦听器并进行处理。

清单12显示的是一个示例

清单12.使用XML文件:流解析
require 'rexml/document'

require 'rexml/streamlistener'

include REXML

class Listener

  include StreamListener

  def tag_start(name, attributes)

    puts "Start #{name}"

  end

  def tag_end(name)

    puts "End #{name}"

  end

end

listener = Listener.new

parser = Parsers::StreamParser.new(File.new("shoppingcart.xml"), listener)

parser.parse

清单13显示了输出

清单13.使用XML文件:流解析输出
Start cart

Start item

Start price

End price

Start qty

End qty

End item

Start item

Start price

End price

Start qty

End qty

End item

Start item

Start price

End price

Start qty

End qty

End item

Start item

Start price

End price

Start qty

End qty

End item

End cart

因此,REXML和Ruby为您提供了强大的组合,使您可以以非常有效和直观的方式使用和处理XML数据。

摘要

Ruby拥有大量内置和外部库,可用于快速,强大和高效的文本处理。 您可以利用此功能来简化和增强您可能会遇到的各种文本数据处理需求。 本文仅涉及Ruby这种功能的一些方面。 您可以取得更多成就。

Ruby绝对是一个很棒的工具,需要在工具箱中使用。


翻译自: https://www.ibm.com/developerworks/xml/library/x-rubytextproc/index.html

ruby 读取文本

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值