【问题标题】:parsing a large text file into 140 character tweets将大文本文件解析为 140 个字符的推文
【发布时间】:2011-11-14 22:38:23
【问题描述】:

我想解析一个大文本文件,以便它在 140 个字符处换行……或一条推文的字符限制。有人有什么想法吗?

谢谢。

【问题讨论】:

  • 您有兴趣使用哪种语言?
  • @zrvan 很可能是 PHP,因为我试图最终将脚本作为 cron 作业运行

标签: php parsing text


【解决方案1】:
ArrayList tweetList = new ArrayList();

while(string.length > 0)
{
     if(string.length > 139)
     {
          tweetList.add(string.substring(0, 139);
          string = string.substring(140,string.length - 1);
     }
     else
     {
         tweetList.add(string.substring(0, string.length - 1);
         string = "";
     }
}

【讨论】:

    【解决方案2】:

    短得多::)

    String[] tweets = yourLongString.split("(?<=\\G.{140})");
    

    糟糕,没有读取 php 约束。这是 Java。

    【讨论】:

      【解决方案3】:

      如果您不关心拆分发生的位置(可能在单词的中间,或类似的地方):

      define ('TWEET_SIZE', 140);
      $parts = str_split ($data, TWEET_SIZE);
      $new = implode ("\n", $parts);
      

      更新 像这样的:

      define ('TWEET_SIZE', 140); // set the size of each segment
      $data = file_get_contents ('<path to file>'); // load the data from file
      $parts = str_split ($data, TWEET_SIZE); // split the data
      $new = implode ("\n", $parts); // put it back together with newlines
      file_put_contents ('<path to new file>', $data); // put in new file (if needed)
      

      【讨论】:

      • 我可以通过什么方式从外部文件实现这一点?另外,在 140 处截断并不理想,因为我宁愿在 140 减去最后一个完整单词时截断(所以如果最后一个单词超过 140 个字符,则将其作为下一条推文的一部分)
      猜你喜欢
      • 2021-01-16
      • 1970-01-01
      • 2012-10-22
      • 2012-11-08
      • 2019-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多