【发布时间】:2014-07-02 22:47:01
【问题描述】:
我目前正在研究将某些单词更改为莎士比亚单词的代码。我必须提取包含单词的句子并将它们打印到另一个文件中。我必须从每个文件的开头删除 .START 。
首先我用空格分割文件和文本,所以现在我有了单词。接下来,我通过散列迭代单词。哈希键和值来自一个制表符分隔的文件,其结构如下:OldEng/ModernEng (lc_Shakespeare_lexicon.txt)。现在,我正试图弄清楚如何找到找到的每个现代英语单词的确切位置,将其更改为莎士比亚;然后找到带有变化词的句子并将它们打印到不同的文件中。除了最后一部分之外,大部分代码都已完成。到目前为止,这是我的代码:
#!/usr/bin/perl -w
use diagnostics;
use strict;
#Declare variables
my $counter=();
my %hash=();
my $conv1=();
my $conv2=();
my $ssph=();
my @text=();
my $key=();
my $value=();
my $conversion=();
my @rmv=();
my $splits=();
my $words=();
my @word=();
my $vals=();
my $existingdir='/home/nelly/Desktop';
my @file='Sentences.txt';
my $eng_words=();
my $results=();
my $storage=();
#Open file to tab delimited words
open (FILE,"<", "lc_shakespeare_lexicon.txt") or die "could not open lc_shakespeare_lexicon.txt\n";
#split words by tabs
while (<FILE>){
chomp($_);
($value, $key)= (split(/\t/), $_);
$hash{$value}=$key;
}
#open directory to Shakespearean files
my $dir="/home/nelly/Desktop/input";
opendir(DIR,$dir) or die "can't opendir Shakespeare_input.tar.gz";
#Use grep to get WSJ file and store into an array
my @array= grep {/WSJ/} readdir(DIR);
#store file in a scalar
foreach my $file(@array){
#open files inside of input
open (DATA,"<", "/home/nelly/Desktop/input/$file") or die "could not open $file\n";
#loop through each file
while (<DATA>){
@text=$_;
chomp(@text);
#Remove .START
@rmv=grep(!/.START/, @text);
foreach $splits(@rmv){
#split data into separate words
@word=(split(/ /, $splits));
#Loop through each word and replace with Shakespearean word that exists
$counter=0;
foreach $words(@word){
if (exists $hash{$words}){
$eng_words= $hash{$words};
$results=$counter;
print "$counter\n";
$counter++;
#create a new directory and store senteces with Shakespearean words in new file called "Sentences.txt"
mkdir $existingdir unless -d $existingdir;
open my $FILE, ">>", "$existingdir/@file", or die "Can't open $existingdir/conversion.txt'\n";
#print $FILE "@words\n";
close ($FILE);
}
}
}
}
}
close (FILE);
close (DIR);
【问题讨论】:
-
你能发布一些输入数据吗?
-
在需要之前声明变量,您会失去
my的一些好处。此外,所有这些分配(my $existingdir='/home/nelly/Desktop'; my @file='Sentences.txt';除外)都是无用的。 -
您很可能会使用
indexpos等 - 就像在这个similar SO question (take a look at the answers) 中一样。我不知道您是否在这里正确设置了查找%hash。尝试使用Data::Dumper或Data::Printer来查看它是如何填写的。 -
文件中的句子是如何存储的?每行一个句子? Perl 代码有几个问题,请尝试在顶部添加
use warnings;,然后解决警告消息。 -
最好有
use warnings而不是-w。此外,DATA是 Perl 的一个特殊文件句柄名称,因此您不应该将它用于您自己的文件。当前的最佳实践是对文件句柄使用词法变量 (open my $in_fh, '<', $file_name or die $!)。
标签: perl