ValueError:找不到子字符串,请救救我

问题描述 投票:0回答:2

因此,我正在尝试创建一种排序器,用于按时间顺序在纸上对文本进行排序。

算法:

def ordered(o, p):
    return sorted(o, key=lambda x: p.index(x))

print(ordered(text, ee))

不幸的是,它返回了:

ValueError: substring not found

我尝试更改参数,因为上次运行它可以正常工作。有人能帮我吗?预先感谢。

这里是文本:

ee = '''
The Civil War: Secession and Strengths/Weaknesses

Secession
The 1860 presidential race showed just how divided the nation had become. The Republicans were united behind Lincoln. The Democrats, however, had split between Northern and Southern factions [faction: a group of people within a larger group who have different ideas from the main group] , with Northern Democrats nominating Stephen Douglas for president and Southern Democrats supporting John C. Breckinridge of Kentucky. The election became even more confusing when a group called the Constitutional Union Party nominated John Bell of Tennessee.
Abraham Lincoln Is Elected President With his opposition divided three ways, Lincoln sailed to victory, but it was an odd victory. Lincoln won the presidential election with just 40 percent of the votes, all of them cast in the North. In ten Southern states, he was not even on the ballot.
For white Southerners, the election of 1860 delivered an unmistakable message. The South was now in the minority. It no longer had the power to shape national events or policies, and Southerners feared that, sooner or later, Congress would try to abolish slavery. And that, wrote a South Carolina newspaper, would mean “the loss of liberty, property, home, country—everything that makes life worth having.”
The South Secedes from the Union In the weeks following the election, talk of secession filled the air. Alarmed senators formed a committee to search for yet another compromise that might hold the nation together. They knew that finding one would not be easy, but they still had to do something to stop the rush toward disunion and disaster.
The Senate committee held its first meeting on December 20, 1860. Just as the senators began their work, events in two distant cities dashed their hopes for a settlement.
In Illinois, a senator named Lyman Trumbull asked President-Elect Abraham Lincoln whether he could support a compromise on slavery. Lincoln's answer was clear. He would not interfere with slavery in the South, and he would support enforcement of the Fugitive Slave Act. However, Lincoln drew the line at letting slavery extend into the territories. On this question, he declared, “Let there be no compromise.”
Meanwhile, in Charleston, South Carolina, delegates attending a state convention voted that same day—December 20, 1860—to leave the Union. The city went wild as church bells rang and crowds filled the streets, roaring their approval. A South Carolina newspaper boldly proclaimed, “The Union Is Dissolved!” Six more states soon followed South Carolina's lead, and in February 1861, those states joined together as the Confederate States of America.
The Civil War Begins On March 4, 1861, Lincoln became president of the not-so-united United States. In his inaugural address, Lincoln stated his belief that secession was both wrong and unconstitutional. He then appealed to the rebellious states to return in peace. “In your hands, my dissatisfied fellow countrymen, and not in mine,” he said, “is the momentous issue of civil war.”

The following month on April 12, 1861, Confederates in Charleston, South Carolina, forced the issue when they opened fire on Fort Sumter, a federal fort in Charleston Harbor. After more than 30 hours of heavy shelling, the defenders of the fort hauled down the Stars and Stripes and replaced it with the white flag of surrender.
The news that the Confederates had fired on the American flag unleashed a wave of patriotic fury in the North. All the doubts that people had about using force to save the Union vanished. A New York newspaper reported excitedly, “There is no more thought of bribing or coaxing the traitors who have dared to aim their cannon balls at the flag of the Union . . . Fort Sumter is temporarily lost, but the country is saved.”
The time for compromise was over. The issues that had divided the nation for so many years would now be decided by a civil war.








North Versus South
President Abraham Lincoln's quick-and-clear response to the attack on Fort Sumter was to call for 75,000 volunteers to come forward to preserve the Union. At the same time, Jefferson Davis, the newly elected president of the Confederacy, called for volunteers to defend the South. For the first time, Americans were fighting a civil war.
Strengths and Weaknesses of the North The North began the war with impressive strengths. Its population was about 22 million, compared to the South's 9 million. Additionally, with about 90 percent of the nation's manufacturing and most of its banks, the North was both richer and more technologically advanced than the South.
The North had geographic advantages, too. It had more farms than the South to provide food for troops, and its land contained most of the country's iron, coal, copper, and gold. The North controlled the seas, and its 21,000 miles of railroad track allowed troops and supplies to be transported wherever they were needed.
The North's greatest weakness was its military leadership. At the start of the war, about one-third of the nation's military officers resigned and returned to their homes in the South. During much of the war, Lincoln searched for effective generals who could lead the Union to victory.
Strength and Weaknesses of the South In contrast to the North, the South's great strength was its military leadership. Most of America's best military officers were Southerners who chose to fight for the Confederacy, which was not an easy decision for many of them. Colonel Robert E. Lee, for example, was not a supporter of either slavery or secession, but he decided that he could not fight against his native Virginia. Lee resigned from the U.S. Army to become commander in chief of the Confederate forces.
The South had geographic advantages as well. To win the war, the North would have to invade and conquer the South, but the sheer size of the South made this a daunting task. The South, in contrast, could win simply by defending its territory until Northerners became tired of fighting.
The South did have an important geographic disadvantage. If the Union gained control of the Mississippi River, it would divide the Confederacy in two.
The South's main weaknesses were its economy and its transportation systems. The region's agriculturally based economy could not support a long war, and the South had few factories to produce guns and other military supplies. The Confederacy also faced serious transportation problems because the South lacked the railroads needed to haul troops and supplies over long distances.
Abraham Lincoln Versus Jefferson Davis The North's greatest advantage was its newly elected president, Abraham Lincoln. Through even the darkest days of the war, Lincoln never wavered from his belief that the Union was perpetual—never to be broken. Throughout his presidency, Lincoln related the preservation of the Union to the ideals of the American Revolution. In his first inaugural address, he said that the Union was begun by the American Revolution, “matured and continued” by the Declaration of Independence, and affirmed by the Constitution.
At the time of the secession crisis, Jefferson Davis was a U.S. senator from Mississippi. A firm believer in states' rights, he resigned his seat in the Senate when Mississippi left the Union. Like Lincoln, Davis often spoke of the American Revolution. When Southerners formed their own government, Davis said in his inaugural address, they “merely asserted a right which the Declaration of Independence of 1776 had defined to be inalienable.” He believed the South was fighting for the same freedom cherished by the nation's founders.









    '''

这里是提取的文本,必须按功能排序:

text = ['in Charleston, South Carolina',
        'On March 4, 1861',
        'In his inaugural address',
        'six more states soon followed south carolina',
        'Confederates in charleston, south carolina',
        'after more than 30 hours of heavy shelling',
        'The time for a compromise was over',
        'The news that the confederates had been fired',
        'Republican candidate abraham lincoln won']

输出,我不知道。我正在运行它,以便可以在大文本中找到这些摘录的确切顺序。

python sorting valueerror
2个回答
1
投票

str.index找不到您要搜索的子字符串时,会发生错误。您可以在一个更简单的示例中看到它:

"some string".index("foo") # not found, raises ValueError

有几种方法可以解决此问题。

一种选择是使用另一种字符串方法来搜索您的子字符串。 str.find方法以与str.index相同的方式搜索子字符串,但是它返回-1而不是如果找不到子字符串则引发异常。那可能是您想要的,也可能不是您想要的,因为它将在所有匹配的子字符串之前将不匹配的子字符串排序。

[另一种选择是先过滤您的输入以查看哪些字符串不匹配,然后再尝试在它们上调用index以查找完全匹配的where。可能是您可以通过某种方式对其进行转换以修复问题,或者可以跳过这些子字符串。例如:

text = [substring for substring in text if substring in ee] # exclude non-matching strings

最后一个选择是确定这是您输入数据的问题,并从源头修复它。也许您不应该有任何不匹配的子字符串。如果是这样,您应该找出哪些不匹配以及为什么不匹配,然后修复它们!我要注意的是,您在几个字符串中都有一些大写字母(例如“ abraham lincoln”和“ south carolina”),如果正文中的大写字母不同,则这些字符串将不匹配。在这种情况下,从str.index中获取异常是一个功能,而不是错误,因为它指出了数据错误!


1
投票

问题是在文本中找不到text列表中的某些字符串,这就是index()引发ValueError异常的原因。您可以在排序之前过滤数据并排除其他元素,或者使用find()而不是index(),因为如果找不到元素,它会返回-1(而不是引发异常)。使用后一种方法,您将获得一个列表,其中文本中未找到的元素位于开头,可能与您的目标不符。

© www.soinside.com 2019 - 2024. All rights reserved.