【发布时间】:2011-11-14 22:38:23
【问题描述】:
我想解析一个大文本文件,以便它在 140 个字符处换行……或一条推文的字符限制。有人有什么想法吗?
谢谢。
【问题讨论】:
-
您有兴趣使用哪种语言?
-
@zrvan 很可能是 PHP,因为我试图最终将脚本作为 cron 作业运行
我想解析一个大文本文件,以便它在 140 个字符处换行……或一条推文的字符限制。有人有什么想法吗?
谢谢。
【问题讨论】:
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 = "";
}
}
【讨论】:
短得多::)
String[] tweets = yourLongString.split("(?<=\\G.{140})");
糟糕,没有读取 php 约束。这是 Java。
【讨论】:
如果您不关心拆分发生的位置(可能在单词的中间,或类似的地方):
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)
【讨论】: