gpt4 book ai didi

c# - 如何使用 LinqToTwitter 获取推文的 HTML?

转载 作者:太空狗 更新时间:2023-10-29 22:08:28 27 4
gpt4 key购买 nike

我最近从 TweetSharp 切换到 LinqToTwitter,我缺少的一件事是一种将推文检索为 HTML 的方法。

TweetSharp 有一个名为 .TextAsHtml() 的方法,它会自动链接提及、哈希标签和超链接。

有谁知道 LinqtoTwitter 中是否存在这样的功能?对 TweetSharp 如何实现这一目标的任何见解都将非常适用。

更新:

看起来 TweetSharp 使用正则表达式来匹配 URL、提及和散列标签。这是一个示例:

private static readonly Regex _parseUrls = new Regex("\\b(([\\w-]+://?|www[.])[^\\s()<>]+(?:\\([\\w\\d]+\\)|([^\\p{P}\\s]|/)))", RegexOptions.IgnoreCase | RegexOptions.Compiled);
private static readonly Regex _parseMentions = new Regex("(^|\\W)@([A-Za-z0-9_]+)", RegexOptions.IgnoreCase | RegexOptions.Compiled);
private static readonly Regex _parseHashtags = new Regex("[#]+[A-Za-z0-9-_]+", RegexOptions.IgnoreCase | RegexOptions.Compiled);

最佳答案

这是我的最终解决方案,它使用了 TweetSharp 库中的一些逻辑。一切顺利:

/// <summary>
/// Extends the LinqToTwitter Library
/// </summary>
public static class TwitterExtensions
{
private static readonly Regex _parseUrls = new Regex("\\b(([\\w-]+://?|www[.])[^\\s()<>]+(?:\\([\\w\\d]+\\)|([^\\p{P}\\s]|/)))", RegexOptions.IgnoreCase | RegexOptions.Compiled);
private static readonly Regex _parseMentions = new Regex("(^|\\W)@([A-Za-z0-9_]+)", RegexOptions.IgnoreCase | RegexOptions.Compiled);
private static readonly Regex _parseHashtags = new Regex("[#]+[A-Za-z0-9-_]+", RegexOptions.IgnoreCase | RegexOptions.Compiled);

/// <summary>
/// Parse Status Text to HTML equivalent
/// </summary>
/// <param name="status">The LinqToTwitter <see cref="Status"/></param>
/// <returns>Formatted HTML string</returns>
public static string TextAsHtml(this Status status)
{
string tweetText = status.Text;

if (!String.IsNullOrEmpty(tweetText))
{
// Replace URLs
foreach (var urlMatch in _parseUrls.Matches(tweetText))
{
Match match = (Match)urlMatch;
tweetText = tweetText.Replace(match.Value, String.Format("<a href=\"{0}\" target=\"_blank\">{0}</a>", match.Value));
}

// Replace Mentions
foreach (var mentionMatch in _parseMentions.Matches(tweetText))
{
Match match = (Match)mentionMatch;
if (match.Groups.Count == 3)
{
string value = match.Groups[2].Value;
string text = "@" + value;
tweetText = tweetText.Replace(text, String.Format("<a href=\"http://twitter.com/{0}\" target=\"_blank\">{1}</a>", value, text));
}
}

// Replace Hash Tags
foreach (var hashMatch in _parseHashtags.Matches(tweetText))
{
Match match = (Match)hashMatch;
string query = Uri.EscapeDataString(match.Value);
tweetText = tweetText.Replace(match.Value, String.Format("<a href=\"http://search.twitter.com/search?q={0}\" target=\"_blank\">{1}</a>", query, match.Value));
}
}

return tweetText;
}
}

关于c# - 如何使用 LinqToTwitter 获取推文的 HTML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7855347/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com