【问题标题】:Skipping lines that contains only whitespace in R跳过 R 中仅包含空格的行
【发布时间】:2016-06-11 09:39:57
【问题描述】:

我在阅读某些 html 子网站时遇到问题。它们中的大多数都可以正常工作,但例如 http://www-history.mcs.st-andrews.ac.uk/Biographies/De_Morgan.html 在 H1 和 H3 中有空行。因此,当涉及到这些人时,我的 data.frame 完全是一团糟,例如: data frame example。框架包含 4 列“姓名”“出生日期和地点”“死亡日期和地点”“链接”。我应该在 LaTeX 中制作一个表格,但是由于那些带有空格的行,我的选项卡在某些时候会出现错误的方向,并且一个人的名字是他的出生日期等等。要阅读该网站,我只需使用从 j=1 到长度的循环(LinkiWlasciwy)

matematyk=LinkWlasciwy[j] %>% read_html() %>% html_nodes(selektor1) %>% html_text()

其中 selektor1="h3 字体 , h1"。之后,我将其保存到 .txt 文件中,并在另一个脚本中读取它,我应该根据这些数据制作 .tex 文件。在我看来,最好只删除文件中仅包含空格的行,例如空格,\n 等。在我的 txt 文件中,例如

玛丽-苏菲·热尔曼| 1776 年 4 月 1 日

在法国巴黎| 1831 年 6 月 27 日

在法国巴黎|www-history.mcs.st-andrews.ac.uk/Biographies/Germain.html|

我使用“|”作为分隔符。不是所有的都是一样的,有的只包含一个空格,有的只有两个等等。我想要的只是把每一个错误的记录都带到这个

玛丽-苏菲·热尔曼| 1776 年 4 月 1 日在法国巴黎| 1831 年 6 月 27 日,法国巴黎|www-history.mcs.st-andrews.ac.uk/Biographies/Germain.html|

我不得不从文本示例中删除 http://,因为我还没有 10 名声望,它们被算作链接

【问题讨论】:

标签: html r dataframe


【解决方案1】:

你可以使用库stringi:

library(stringi)
line<-c("Marie-Sophie Germain| 1 April 1776",
" ",
"in Paris, France| 27 June 1831",
"   ",
"in Paris, France|www-history.mcs.st-andrews.ac.uk/Biographies/Germain.html|")

line2<- line[stri_count_regex(line, "^[ \\t]+$") ==0]
line2
stri_paste(line2, collapse="")

结果:

[1] "Marie-Sophie Germain| 1 April 1776in Paris, France| 27 June 1831in Paris, France|www-history.mcs.st-andrews.ac.uk/Biographies/Germain.html|"

【讨论】:

  • 感谢您的宝贵时间,但在 gsub 中使用 ([^ \t\r\n])[ \t]+$ 解决了一切问题。
猜你喜欢
  • 2012-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多