gpt4 book ai didi

regex - R - data.frame 的原始文本

转载 作者:行者123 更新时间:2023-12-02 09:30:17 25 4
gpt4 key购买 nike

我处理来自扫描目录的原始文本数据。我想将我的字符串向量转换为 data.frame 对象。我的向量由执行每一项或多项工作的人员的字母顺序列表组成。
- 人名大写。
- 每件作品都有编号。
- 编号工作是连续的。


AADFDS
1 Lorem ipsum dolor sit amet, consectetur adipiscing elit.
AB
2 Nulla sollicitudin elit in purus egestas, in placerat velit iaculis.
BBDDED
3 Nunc et eros eget turpis sollicitudin mollis id et mi.
4 Mauris condimentum velit eu consequat feugiat.
5 Suspendisse sit amet metus vitae est eleifend tincidunt.
CCDDFSF
6 Sed cursus augue in tempus scelerisque.
7 in commodo enim in laoreet gravida.

预期结果1

Author     Work  
AA DFDS 1 Lorem ipsum dolor sit amet, consectetur adipiscing elit.
AB 2 Nulla sollicitudin elit in purus egestas, in placerat velit
BBDDED 3 Nunc et eros eget turpis sollicitudin mollis id et
BBDDED 4 Mauris condimentum velit eu consequat feugiat.
BBDDED 5 Suspendisse sit amet metus vitae est eleifend tincidunt.
CCDDFSF 6 Sed cursus augue in tempus scelerisque.
CCDDFSF 7 in commodo enim in laoreet gravida.

预期结果 2,每项工作都有一列

Author  |   Work1  |  Work2  |  Work3  |  Work(x)  

数据导入到 R 中:

readlines ("clipboard", encoding = "latin1 ")

我能够使用不同的正则表达式识别包含大写字母艺术家姓名的行

例如

^[A-ZÁÀÂÄÃÅÇÉÈÊÈÍÌÈÏÑÓÒÔÖÕÚÙÛÜÝYÆO][A-ZÁÀÂÄãÅÇÉÈÊÈÍÌÈÏÏÙÛÜÝYÆO |']

我能够识别包括艺术品在内的线条

^[0-9]+[\s]

如有任何帮助,我们将不胜感激。

最佳答案

这为您的示例数据提供了正确的结果。

txt="
AADFDS
1 Lorem ipsum dolor sit amet, consectetur adipiscing elit.
AB
2 Nulla sollicitudin elit in purus egestas, in placerat velit iaculis.
BBDDED
3 Nunc et eros eget turpis sollicitudin mollis id et mi.
4 Mauris condimentum velit eu consequat feugiat.
5 Suspendisse sit amet metus vitae est eleifend tincidunt.
CCDDFSF
6 Sed cursus augue in tempus scelerisque.
7 in commodo enim in laoreet gravida."

last_author=""
author_count=0
#the first scan splits the data by line, i.e., sep="\n"
#then for each line, we split by whitespace, i.e., sep=" "
#if the first element is numeric we increase the
#respective author's work counter "author_count" and
#we return the the work in a data.frame
#if the first element is non-numeric, we have
#encountered a new author
#we store the new author name in "last_author"
#(and remove trailing whitespaces at the end)
result1=do.call("rbind",
lapply(as.list(scan(text=txt,
what="character",
sep="\n",
quiet=TRUE)),
function(x) {
tmp=scan(text=x,what="character",sep=" ",quiet=TRUE)
if (grepl("[0-9]",tmp[1])) {
author_count<<-author_count+1
data.frame(Author=last_author,N=author_count,Work=x)
} else {
last_author<<-gsub("\\s*$","",x)
author_count<<-0
NULL
}}))

#we pivot the data; rows correspond to authors, columns to works
result2=reshape2::dcast(result1,Author~N,value.var = "Work")
#just renaming the columns
colnames(result2)[-1]=paste0("Work",1:(ncol(result2)-1))
result2

关于regex - R - data.frame 的原始文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33842315/

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