【问题标题】:Select a specific text form .TXT and group the content从 .TXT 中选择特定文本并将内容分组
【发布时间】:2015-02-06 10:21:30
【问题描述】:

我想为数据可视化选择特定文本。 我的计划是从文本文件中选择文本

 文件.txt 

这个文件看起来像这样

 瑞士 (SUI) # - 23 名球员
(1) GK Pascal Zuberbühler ## 40,巴塞尔 (SUI)
(12) GK Diego Benaglio ## 1,国家队 (POR)
(21 ) GK Fabio Coltorti ## 2,Grasshoppe (SUI)
(3) DF Ludovic Magnin ## 30,斯图加特 (GER)

我要选择

(SUI), (POR), (SUI) & (GER)

所以我做了一个正则表达式

#\W([A-Z]){3}\S#

这是我已经编写的代码

$myfile = fopen("2006/ch-switzerland.txt", "r") or die("无法打开文件!");
    echo fread($myfile,filesize("2006/ch-switzerland.txt"));
    fclose($myfile);

所以现在我想选择特定的文本并将其分组以便我看到

(SUI)2, (POR), (GER)

我的 PHP 技术不是很好,所以希望你能帮助我。

感谢您的宝贵时间;)

【问题讨论】:

    标签: php regex r


    【解决方案1】:

    使用file_get_contents,可以更轻松地读取文件。但是,由于您似乎想跳过第一行(命名足球队),我更喜欢将文件作为行来读取。这可以通过file 完成。

    另外,您不需要在正则表达式字母周围加上圆括号:#\W[A-Z]{3}\S#

    <?php
    
    # We use an array for counting
    $counts = array();
    
    # Read the file lines into an array
    $lines = file('test.txt');
    
    # Iterate over all lines but the first (1 means we start at line 1, instead of 0)
    foreach (array_slice($lines, 1) as $line) {
        # Do the regular expression and check if it was a match
        $was_match = preg_match('#\W[A-Z]{3}\S#', $line, $match);
        if ($was_match)
        {
            # check if we already counted this country
            if (!isset($counts[$match[0]]))
                $counts[$match[0]] = 0; # if not, set count to initial zero
    
            # increment the country count by one
            $counts[$match[0]] += 1;
        }
    }
    
    var_dump($counts);
    
    // array(3) {
    //   ["(SUI)"]=>
    //   int(2)
    //   ["(POR)"]=>
    //   int(1)
    //   ["(GER)"]=>
    //   int(1)
    // }
    

    【讨论】:

    • 非常感谢。这对我有用!谢谢你的负担。 (小细节你忘记了
       if (!isset($counts[$match[0]]))
    • 你的意思是卷曲的{}?在大多数具有 C 风格语法的语言中(在 PHP 中也是如此),如果 只有一个 语句后跟,则不需要大括号。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-28
    相关资源
    最近更新 更多