13

私はいくつかのWebスクレイピングを行っています。これはデータの形式です

Sr.No.  Course_Code Course_Name Credit  Grade   Attendance_Grade

私が受け取る実際の文字列は次の形式です

1 CA727 PRINCIPLES OF COMPILER DESIGN 3 A M

私が興味を持っているのは、Course_Code、Course_Name、および Grade です。この例では、値は次のようになります。

Course_Code : CA727
Course_Name : PRINCIPLES OF COMPILER DESIGN
Grade : A

文字列を手動で解析する代わりに、正規表現またはその他の手法を使用してこの情報を簡単に抽出する方法はありますか? jruby を 1.9 モードで使用しています。

4

5 に答える 5

42

Ruby の名前付きキャプチャと自己記述型正規表現を使用しましょう!

course_line = /
    ^                  # Starting at the front of the string
    (?<SrNo>\d+)       # Capture one or more digits; call the result "SrNo"
    \s+                # Eat some whitespace
    (?<Code>\S+)       # Capture all the non-whitespace you can; call it "Code"
    \s+                # Eat some whitespace
    (?<Name>.+\S)      # Capture as much as you can
                       # (while letting the rest of the regex still work)
                       # Make sure you end with a non-whitespace character.
                       # Call this "Name"
    \s+                # Eat some whitespace
    (?<Credit>\S+)     # Capture all the non-whitespace you can; call it "Credit"
    \s+                # Eat some whitespace
    (?<Grade>\S+)      # Capture all the non-whitespace you can; call it "Grade"
    \s+                # Eat some whitespace
    (?<Attendance>\S+) # Capture all the non-whitespace; call it "Attendance"
    $                  # Make sure that we're at the end of the line now
/x

str = "1   CA727   PRINCIPLES OF COMPILER DESIGN   3   A   M"
parts = str.match(course_line)

puts "
Course Code: #{parts['Code']}
Course Name: #{parts['Name']}
      Grade: #{parts['Grade']}".strip

#=> Course Code: CA727
#=> Course Name: PRINCIPLES OF COMPILER DESIGN
#=>       Grade: A
于 2012-06-05T21:35:37.367 に答える
6

楽しみのためだけに:

str = "1 CA727 PRINCIPLES OF COMPILER DESIGN 3 A M"
tok = str.split /\s+/
data = {'Sr.No.' => tok.shift, 'Course_Code' => tok.shift, 'Attendance_Grade' => tok.pop,'Grade' => tok.pop, 'Credit' => tok.pop, 'Course_Name' => tok.join(' ')}
于 2012-06-06T01:19:47.290 に答える
3

区切り文字が常に 3 つのスペースであることが正しくわかりますか? それからちょうど:

serial_number, course_code, course_name, credit, grade, attendance_grade = 
  the_string.split('   ')
于 2012-06-05T21:34:14.623 に答える
3

コースの説明を除くすべてが単一の単語で構成され、先頭または末尾にスペースがないと仮定します。

/^(\w+)\s+(\w+)\s+([\w\s]+)\s+(\w+)\s+(\w+)\s+(\w+)$/

サンプル文字列は、次の一致グループを生成します。

1.  1
2.  CA727
3.  PRINCIPLES OF COMPILER DESIGN
4.  3
5.  A
6.  M
于 2012-06-05T21:36:21.763 に答える
1

この回答はRubyの慣用句ではありません. 説明した問題を解決するために本当に必要なのは、行を空白で分割することだけです。

line = '1   CA727   PRINCIPLES OF COMPILER DESIGN   3   A   M'
array = line.split /\t|\s{2,}/
puts array[1], array[2], array[4]

これは、データが規則的であることを前提としています。そうでない場合は、正規表現を調整し、必要な数のフィールドがない場合のエッジ ケースを処理するために、より多くの作業を行う必要があります。

後世のためのメモ

OP は入力文字列を変更し、区切り文字をフィールド間の単一のスペースに変更しました。あまり具体的でないケースでは、OP以外の他の人に役立つ可能性があるため、元の質問への回答をそのまま残します(参照用の元の入力文字列を含む)。

于 2012-06-05T21:36:38.977 に答える